callscope-ai 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
callscope/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ """callscope: local analysis of customer-service calls."""
2
+
3
+ from .analysis import analyze, contact_reasons, key_moments, sentiment
4
+ from .diarize import diarize
5
+ from .transcribe import transcribe
6
+
7
+ __version__ = "0.1.0"
8
+ SCHEMA = "callscope/1"
9
+ __all__ = ["analyze", "contact_reasons", "diarize", "key_moments", "sentiment", "transcribe", "SCHEMA"]
callscope/analysis.py ADDED
@@ -0,0 +1,100 @@
1
+ """Sentiment, contact reasons, key moments and the one-shot ``analyze``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ from .diarize import diarize
8
+ from .lexicon import MOMENTS, NEGATIVE, NEGATORS, POSITIVE, REASONS
9
+
10
+ SCHEMA = "callscope/1"
11
+ _WORD = re.compile(r"[\w'’-]+", re.UNICODE)
12
+
13
+
14
+ def _words(text: str) -> list[str]:
15
+ return [w.lower() for w in _WORD.findall(text)]
16
+
17
+
18
+ def _score(text: str) -> float:
19
+ words = _words(text)
20
+ score = 0
21
+ for i, w in enumerate(words):
22
+ sign = 1 if w in POSITIVE else -1 if w in NEGATIVE else 0
23
+ if sign and any(p in NEGATORS for p in words[max(0, i - 2):i]):
24
+ sign = -sign
25
+ score += sign
26
+ return max(-1.0, min(1.0, score / 3))
27
+
28
+
29
+ def _has(text: str, keyword: str) -> bool:
30
+ """Whole-word match, so 'down' does not match 'downgrade' nor 'bug' 'debug'."""
31
+ return re.search(r"(?<![\w])" + re.escape(keyword) + r"(?![\w])", text) is not None
32
+
33
+
34
+ def _label(score: float) -> str:
35
+ return "positive" if score > 0.15 else "negative" if score < -0.15 else "neutral"
36
+
37
+
38
+ def sentiment(segments: list[dict]) -> dict:
39
+ """Sentiment per segment (-1..1) plus the customer's curve over the call."""
40
+ per = [{"index": i, "start": s["start"], "speaker": s.get("speaker"), "score": round(_score(s["text"]), 2),
41
+ "label": _label(_score(s["text"]))} for i, s in enumerate(segments)]
42
+ cust = [p for p in per if p["speaker"] == "customer"] or per
43
+ curve = [{"start": p["start"], "score": p["score"]} for p in cust]
44
+ mean = round(sum(p["score"] for p in cust) / len(cust), 2) if cust else 0.0
45
+ half = len(cust) // 2
46
+ trend = 0.0
47
+ if half:
48
+ trend = round(sum(p["score"] for p in cust[half:]) / (len(cust) - half) - sum(p["score"] for p in cust[:half]) / half, 2)
49
+ return {"segments": per, "customer_curve": curve, "customer_mean": mean, "customer_trend": trend}
50
+
51
+
52
+ def contact_reasons(segments: list[dict]) -> list[dict]:
53
+ """Ranked contact reasons, from the customer's words (all speakers if unlabelled)."""
54
+ cust = [s for s in segments if s.get("speaker") == "customer"] or segments
55
+ text = " ".join(s["text"].lower() for s in cust)
56
+ found = []
57
+ for reason, kws in REASONS.items():
58
+ hits = sorted({k for k in kws if _has(text, k)})
59
+ if hits:
60
+ found.append({"reason": reason, "matches": hits, "score": len(hits)})
61
+ return sorted(found, key=lambda r: (-r["score"], r["reason"]))
62
+
63
+
64
+ def key_moments(segments: list[dict]) -> list[dict]:
65
+ """Complaints and churn threats (customer), promises (agent)."""
66
+ owner = {"complaint": "customer", "churn_threat": "customer", "agent_promise": "agent"}
67
+ out = []
68
+ for i, s in enumerate(segments):
69
+ low = s["text"].lower()
70
+ for kind, kws in MOMENTS.items():
71
+ if s.get("speaker") not in (None, owner[kind]):
72
+ continue
73
+ hit = next((k for k in kws if _has(low, k)), None)
74
+ if hit:
75
+ out.append({"type": kind, "segment": i, "start": s["start"], "speaker": s.get("speaker"),
76
+ "text": s["text"], "match": hit})
77
+ return out
78
+
79
+
80
+ def analyze(source, **transcribe_options) -> dict:
81
+ """Run everything. ``source`` is an audio path or a list of segments.
82
+
83
+ The returned dict is the common callscope format (``schema`` = ``callscope/1``).
84
+ """
85
+ if isinstance(source, str) or hasattr(source, "__fspath__"):
86
+ from .transcribe import transcribe
87
+ segments = transcribe(str(source), **transcribe_options)
88
+ origin = str(source)
89
+ else:
90
+ segments, origin = list(source), None
91
+ segments = diarize(segments)
92
+ return {
93
+ "schema": SCHEMA,
94
+ "source": origin,
95
+ "duration": max((s["end"] for s in segments), default=0.0),
96
+ "segments": segments,
97
+ "sentiment": sentiment(segments),
98
+ "contact_reasons": contact_reasons(segments),
99
+ "key_moments": key_moments(segments),
100
+ }
callscope/cli.py ADDED
@@ -0,0 +1,31 @@
1
+ import argparse
2
+ import json
3
+ import sys
4
+
5
+ from . import analyze
6
+ from .demo import DEMO_SEGMENTS
7
+
8
+
9
+ def main(argv=None) -> int:
10
+ p = argparse.ArgumentParser(prog="callscope", description="Analyze a customer-service call locally.")
11
+ sub = p.add_subparsers(dest="cmd", required=True)
12
+ a = sub.add_parser("analyze", help="audio file, or a JSON file of segments")
13
+ a.add_argument("path")
14
+ a.add_argument("--model", default="small", help="faster-whisper model size (audio only)")
15
+ a.add_argument("--language", default=None)
16
+ sub.add_parser("demo", help="analyze a fictional call, no audio or model needed")
17
+ args = p.parse_args(argv)
18
+ if args.cmd == "demo":
19
+ result = analyze(DEMO_SEGMENTS)
20
+ elif args.path.endswith(".json"):
21
+ with open(args.path, encoding="utf-8") as f:
22
+ result = analyze(json.load(f))
23
+ else:
24
+ result = analyze(args.path, model_size=args.model, language=args.language)
25
+ json.dump(result, sys.stdout, ensure_ascii=False, indent=2)
26
+ print()
27
+ return 0
28
+
29
+
30
+ if __name__ == "__main__":
31
+ raise SystemExit(main())
callscope/demo.py ADDED
@@ -0,0 +1,10 @@
1
+ """A fictional call (no real recording)."""
2
+
3
+ DEMO_SEGMENTS = [
4
+ {"start": 0.0, "end": 4.0, "text": "Bonjour, vous parlez à Camille, comment puis-je vous aider ?"},
5
+ {"start": 5.5, "end": 12.0, "text": "Bonjour, j'ai un problème avec ma facture, on m'a prélevé deux fois ce mois-ci, c'est inadmissible."},
6
+ {"start": 12.5, "end": 16.0, "text": "Je suis désolée, je vais vérifier tout de suite votre dossier."},
7
+ {"start": 18.0, "end": 24.0, "text": "J'en ai marre, c'est la deuxième fois. Si ça continue je vais résilier et changer d'opérateur."},
8
+ {"start": 24.5, "end": 31.0, "text": "Je comprends. Je m'engage à vous rembourser, et je vous rappelle avant demain pour confirmer."},
9
+ {"start": 33.0, "end": 36.0, "text": "D'accord, merci, c'est très bien."},
10
+ ]
callscope/diarize.py ADDED
@@ -0,0 +1,51 @@
1
+ """Who speaks when: ``agent`` or ``customer``.
2
+
3
+ Heuristic and fully local. Priority: an existing ``speaker``/``channel`` field
4
+ on the segment, then turn-taking on silence gaps with opening-phrase cues.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+
11
+ AGENT_CUES = re.compile(
12
+ r"(vous parlez à|comment puis-je|puis-je vous aider|je vais (vérifier|regarder|noter)|"
13
+ r"how can i help|you('re| are) speaking with|let me (check|look))",
14
+ re.I,
15
+ )
16
+ ROLES = ("agent", "customer")
17
+
18
+
19
+ def diarize(segments: list[dict], channel_roles: dict[int, str] | None = None, gap: float = 0.4) -> list[dict]:
20
+ """Return new segments with a ``speaker`` of ``agent`` or ``customer``.
21
+
22
+ ``channel_roles`` maps a stereo channel number to a role, e.g. ``{0: "agent", 1: "customer"}``.
23
+ """
24
+ out = [dict(s) for s in segments]
25
+ for s in out:
26
+ # Labels from other tools (e.g. "SPEAKER_00") are not roles: guess them.
27
+ if "speaker" in s and s["speaker"] not in ROLES:
28
+ s["original_speaker"] = s.pop("speaker")
29
+ if s.get("speaker") in ROLES:
30
+ continue
31
+ if channel_roles and s.get("channel") in channel_roles:
32
+ s["speaker"] = channel_roles[s["channel"]]
33
+ current = 0 # index into ROLES for the running turn
34
+ first = next((s for s in out if "speaker" not in s), None)
35
+ if first is not None and AGENT_CUES.search(first["text"]):
36
+ current = 0
37
+ elif first is not None:
38
+ current = 1
39
+ prev_end = None
40
+ for s in out:
41
+ if "speaker" in s:
42
+ current = ROLES.index(s["speaker"])
43
+ prev_end = s["end"]
44
+ continue
45
+ if prev_end is not None and s["start"] - prev_end >= gap and not AGENT_CUES.search(s["text"]):
46
+ current = 1 - current
47
+ elif AGENT_CUES.search(s["text"]):
48
+ current = 0
49
+ s["speaker"] = ROLES[current]
50
+ prev_end = s["end"]
51
+ return out
callscope/lexicon.py ADDED
@@ -0,0 +1,27 @@
1
+ """Small bilingual (FR/EN) lexicons. Deliberately simple and inspectable."""
2
+
3
+ POSITIVE = {
4
+ "merci", "parfait", "super", "génial", "excellent", "content", "satisfait", "ravi", "bien", "top",
5
+ "thanks", "thank", "great", "perfect", "happy", "excellent", "good", "appreciate",
6
+ }
7
+ NEGATIVE = {
8
+ "inadmissible", "scandaleux", "nul", "énervé", "enervé", "marre", "problème", "probleme", "panne", "arnaque",
9
+ "inacceptable", "déçu", "decu", "plainte", "honteux", "catastrophe", "impossible", "attends",
10
+ "terrible", "angry", "unacceptable", "ridiculous", "broken", "worst", "furious", "disappointed", "complaint",
11
+ }
12
+ NEGATORS = {"pas", "jamais", "ne", "not", "never", "no"}
13
+
14
+ REASONS = {
15
+ "billing": ["facture", "facturation", "prélèvement", "prelevement", "remboursement", "tarif", "invoice", "bill", "refund", "charged"],
16
+ "cancellation": ["résilier", "resilier", "résiliation", "resiliation", "annuler", "cancel", "unsubscribe", "close my account"],
17
+ "outage": ["panne", "coupure", "plus de connexion", "ne marche plus", "ne fonctionne plus", "outage", "not working", "down"],
18
+ "delivery": ["livraison", "colis", "commande", "delivery", "parcel", "order"],
19
+ "technical_support": ["bug", "erreur", "installer", "configurer", "mot de passe", "password", "error", "install"],
20
+ "subscription_change": ["changer d'offre", "forfait", "abonnement", "upgrade", "downgrade", "plan"],
21
+ }
22
+
23
+ MOMENTS = {
24
+ "complaint": ["inadmissible", "scandaleux", "plainte", "inacceptable", "honteux", "complaint", "unacceptable", "ridiculous"],
25
+ "churn_threat": ["résilier", "resilier", "changer d'opérateur", "changer d'operateur", "je pars", "concurrent", "cancel my", "switch to", "leave you"],
26
+ "agent_promise": ["je vous rappelle", "je m'engage", "je vous promets", "avant demain", "sous 48", "i will call you back", "i promise", "within 48"],
27
+ }
@@ -0,0 +1,14 @@
1
+ """Timestamped transcription with faster-whisper (optional dependency)."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ def transcribe(path: str, model_size: str = "small", language: str | None = None, device: str = "cpu") -> list[dict]:
7
+ """Return segments ``[{"start": s, "end": s, "text": str}]``. Runs locally."""
8
+ try:
9
+ from faster_whisper import WhisperModel
10
+ except ImportError as exc: # pragma: no cover - depends on environment
11
+ raise ImportError("Transcription needs faster-whisper: pip install 'callscope-ai[whisper]'") from exc
12
+ model = WhisperModel(model_size, device=device, compute_type="int8")
13
+ segments, _info = model.transcribe(path, language=language, vad_filter=True)
14
+ return [{"start": round(s.start, 2), "end": round(s.end, 2), "text": s.text.strip()} for s in segments]
@@ -0,0 +1,64 @@
1
+ Metadata-Version: 2.5
2
+ Name: callscope-ai
3
+ Version: 0.1.0
4
+ Summary: Local call-center call analysis: transcript, speakers, sentiment, contact reasons and key moments in one JSON.
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Keywords: call-center,customer-service,sentiment,speech,transcription
8
+ Classifier: Environment :: Console
9
+ Classifier: Programming Language :: Python :: 3
10
+ Requires-Python: >=3.10
11
+ Provides-Extra: test
12
+ Requires-Dist: pytest; extra == 'test'
13
+ Provides-Extra: whisper
14
+ Requires-Dist: faster-whisper>=1.0; extra == 'whisper'
15
+ Description-Content-Type: text/markdown
16
+
17
+ # callscope
18
+
19
+ Analyze customer-service calls locally: timestamped transcript, who speaks when, sentiment curve, contact reasons and key moments, in one JSON.
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ pip install callscope-ai # analysis of transcripts (no dependencies)
25
+ pip install "callscope-ai[whisper]" # + local transcription of audio (faster-whisper)
26
+ ```
27
+
28
+ ## Use
29
+
30
+ ```python
31
+ import callscope
32
+
33
+ result = callscope.analyze("call.wav") # audio -> full analysis
34
+ result = callscope.analyze([{"start": 0, "end": 3, "text": "Bonjour, comment puis-je vous aider ?"}])
35
+ ```
36
+
37
+ ```bash
38
+ callscope demo # fictional call, no audio, no model
39
+ callscope analyze call.wav --model small
40
+ callscope analyze segments.json
41
+ ```
42
+
43
+ French and English keyword lexicons are built in; everything runs on your machine.
44
+
45
+ ## Functions
46
+
47
+ | Function | Returns |
48
+ |---|---|
49
+ | `transcribe(path, model_size, language)` | `[{start, end, text}]` (needs the `whisper` extra) |
50
+ | `diarize(segments, channel_roles=None)` | segments with `speaker` = `agent` or `customer` (stereo channels, else turn-taking heuristic) |
51
+ | `sentiment(segments)` | per-segment score (-1..1), customer curve, mean and trend |
52
+ | `contact_reasons(segments)` | ranked reasons: billing, cancellation, outage, delivery, technical_support, subscription_change |
53
+ | `key_moments(segments)` | complaints, churn threats, agent promises |
54
+ | `analyze(source)` | everything above in one dict |
55
+
56
+ ## Output format (`callscope/1`)
57
+
58
+ `analyze()` returns `{schema, source, duration, segments, sentiment, contact_reasons, key_moments}`. This is the shared format for tools built on callscope.
59
+
60
+ ## Limits
61
+
62
+ Lexicon-based sentiment and heuristic speaker separation are simple baselines, not state-of-the-art models.
63
+
64
+ MIT licensed. Run tests with `pip install -e ".[test]" && pytest` (no network).
@@ -0,0 +1,12 @@
1
+ callscope/__init__.py,sha256=m9AJLA2JB9qvv1005-3OGIIi9NFiNw9wRCzfO-kGLzk,354
2
+ callscope/analysis.py,sha256=dX3dtNAOiIFjcXUqyAyK9xDwgoY0fRwDWeVta84o5DY,4050
3
+ callscope/cli.py,sha256=ZqOzAPiOTeGIwkjduNWujineHiLKs1pQ8iH3wsfO4RA,1121
4
+ callscope/demo.py,sha256=mUKHeNHZ4sVnue-TStIu8wO7DWUaENDk0jpxYS8LbpY,802
5
+ callscope/diarize.py,sha256=nHme7hsH5emzHoT2viOYE338ZOcRioh2ymiRgazMMI0,1964
6
+ callscope/lexicon.py,sha256=rZ4NQbFX5fbPnyjh77ZJi4EjnvZDGzjxHjUCEMpxRU0,1899
7
+ callscope/transcribe.py,sha256=afdVrPabefT-uNdmsUb3q6VTauMRUtGY-TcHRXpQSIM,819
8
+ callscope_ai-0.1.0.dist-info/METADATA,sha256=VBw1DpKcxFmD9vR20e01kcJNaK_0qfOUkjxfGd7nKc0,2417
9
+ callscope_ai-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ callscope_ai-0.1.0.dist-info/entry_points.txt,sha256=am_99hLN_-FiVLyuk1ZvON-WVhRvoW3VpF04w4kKlkE,83
11
+ callscope_ai-0.1.0.dist-info/licenses/LICENSE,sha256=OlH0Y-yfmOIUOaoCxpoWBqd807WnKuQDIdIjD1jojUg,1087
12
+ callscope_ai-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ callscope = callscope.cli:main
3
+ callscope-ai = callscope.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jérémie
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.