livedeck 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.
Files changed (167) hide show
  1. livedeck/__init__.py +1 -0
  2. livedeck/__main__.py +111 -0
  3. livedeck/analyzers/__init__.py +135 -0
  4. livedeck/analyzers/heuristic_offline.py +94 -0
  5. livedeck/analyzers/llm_product_fidelity_v1.py +138 -0
  6. livedeck/analyzers/llm_stateful_v1.py +152 -0
  7. livedeck/answer_charts.py +170 -0
  8. livedeck/answer_report_view.py +140 -0
  9. livedeck/answer_results.py +295 -0
  10. livedeck/answer_view.py +446 -0
  11. livedeck/assets/stt_test_en.wav +0 -0
  12. livedeck/assets/stt_test_ja.wav +0 -0
  13. livedeck/audio.py +512 -0
  14. livedeck/audio_playback.py +110 -0
  15. livedeck/audio_wasapi.py +443 -0
  16. livedeck/conversations.py +609 -0
  17. livedeck/core.py +199 -0
  18. livedeck/cue_card_eval.py +353 -0
  19. livedeck/demo_audio_dialog.py +293 -0
  20. livedeck/dialogue.py +947 -0
  21. livedeck/dialogue_charts.py +345 -0
  22. livedeck/dialogue_eval.py +535 -0
  23. livedeck/dialogue_eval_view.py +786 -0
  24. livedeck/dialogue_results.py +308 -0
  25. livedeck/eval_engine.py +1176 -0
  26. livedeck/fixed_cues.py +118 -0
  27. livedeck/generation.py +240 -0
  28. livedeck/glossary.py +216 -0
  29. livedeck/gui.py +2749 -0
  30. livedeck/i18n.py +179 -0
  31. livedeck/intent.py +298 -0
  32. livedeck/intent_badges.py +227 -0
  33. livedeck/llm.py +304 -0
  34. livedeck/locales/en/cues/closing.md +3 -0
  35. livedeck/locales/en/cues/opening.md +3 -0
  36. livedeck/locales/en/cues/self_intro.md +7 -0
  37. livedeck/locales/en/prompts/analyzer_v1.md +34 -0
  38. livedeck/locales/en/prompts/answer_default_v1.md +7 -0
  39. livedeck/locales/en/prompts/preparation_v1.md +9 -0
  40. livedeck/locales/en/prompts/product_fidelity_v1.md +3 -0
  41. livedeck/locales/en/prompts/refiner_v1.md +21 -0
  42. livedeck/locales/en/prompts/responder_choice_cards.md +13 -0
  43. livedeck/locales/en/prompts/responder_cue_card.md +15 -0
  44. livedeck/locales/en/prompts/responder_knowledge_card.md +17 -0
  45. livedeck/locales/en/prompts/responder_strategy_card.md +15 -0
  46. livedeck/locales/en/prompts/spoken_points_v1.md +2 -0
  47. livedeck/locales/en.yaml +648 -0
  48. livedeck/locales/ja/cues/closing.md +3 -0
  49. livedeck/locales/ja/cues/opening.md +3 -0
  50. livedeck/locales/ja/cues/self_intro.md +7 -0
  51. livedeck/locales/ja/prompts/analyzer_v1.md +33 -0
  52. livedeck/locales/ja/prompts/answer_default_v1.md +8 -0
  53. livedeck/locales/ja/prompts/preparation_v1.md +11 -0
  54. livedeck/locales/ja/prompts/product_fidelity_v1.md +3 -0
  55. livedeck/locales/ja/prompts/refiner_v1.md +21 -0
  56. livedeck/locales/ja/prompts/responder_choice_cards.md +14 -0
  57. livedeck/locales/ja/prompts/responder_cue_card.md +16 -0
  58. livedeck/locales/ja/prompts/responder_knowledge_card.md +18 -0
  59. livedeck/locales/ja/prompts/responder_strategy_card.md +16 -0
  60. livedeck/locales/ja/prompts/spoken_points_v1.md +2 -0
  61. livedeck/locales/ja.yaml +648 -0
  62. livedeck/model_manager.py +490 -0
  63. livedeck/model_manager_view.py +320 -0
  64. livedeck/paths.py +407 -0
  65. livedeck/prep_eval.py +492 -0
  66. livedeck/preparation/__init__.py +155 -0
  67. livedeck/preparation/openai_backend.py +45 -0
  68. livedeck/refiner_charts.py +170 -0
  69. livedeck/refiner_eval.py +546 -0
  70. livedeck/refiner_eval_view.py +403 -0
  71. livedeck/refiner_results.py +193 -0
  72. livedeck/refiners/__init__.py +128 -0
  73. livedeck/refiners/llm_refiner_v1.py +393 -0
  74. livedeck/refiners/merge_bubbles_v1.py +147 -0
  75. livedeck/refiners/passthrough.py +45 -0
  76. livedeck/replay.py +80 -0
  77. livedeck/responders/__init__.py +63 -0
  78. livedeck/responders/choice_cards.py +81 -0
  79. livedeck/responders/cue_card.py +66 -0
  80. livedeck/responders/knowledge_card.py +114 -0
  81. livedeck/responders/strategy_card.py +81 -0
  82. livedeck/sample_catalog.py +367 -0
  83. livedeck/sample_workspaces/niihama-beverage-en/cues/closing.md +3 -0
  84. livedeck/sample_workspaces/niihama-beverage-en/cues/opening.md +3 -0
  85. livedeck/sample_workspaces/niihama-beverage-en/cues/self_intro.md +9 -0
  86. livedeck/sample_workspaces/niihama-beverage-en/documents/application_essay.md +7 -0
  87. livedeck/sample_workspaces/niihama-beverage-en/documents/company_overview.md +13 -0
  88. livedeck/sample_workspaces/niihama-beverage-en/documents/company_research_notes.md +14 -0
  89. livedeck/sample_workspaces/niihama-beverage-en/documents/job_description_sales.md +13 -0
  90. livedeck/sample_workspaces/niihama-beverage-en/documents/logistics_and_applications.md +14 -0
  91. livedeck/sample_workspaces/niihama-beverage-en/documents/motivation_and_self_analysis.md +24 -0
  92. livedeck/sample_workspaces/niihama-beverage-en/documents/part_time_and_activities.md +39 -0
  93. livedeck/sample_workspaces/niihama-beverage-en/documents/profile_and_self_intro.md +17 -0
  94. livedeck/sample_workspaces/niihama-beverage-en/documents/seminar_and_thesis_notes.md +17 -0
  95. livedeck/sample_workspaces/niihama-beverage-en/records/index.json +806 -0
  96. livedeck/sample_workspaces/niihama-beverage-en/sessions/2027-04-15_05-30-00-demo1/answers.jsonl +0 -0
  97. livedeck/sample_workspaces/niihama-beverage-en/sessions/2027-04-15_05-30-00-demo1/raw_chunks.jsonl +84 -0
  98. livedeck/sample_workspaces/niihama-beverage-en/sessions/2027-04-15_05-30-00-demo1/session.json +7 -0
  99. livedeck/sample_workspaces/niihama-beverage-en/sessions/2027-04-15_05-30-00-demo1/speech_units.jsonl +84 -0
  100. livedeck/sample_workspaces/niihama-beverage-en/sessions/2027-04-15_05-30-00-demo1/topics.jsonl +0 -0
  101. livedeck/sample_workspaces/niihama-beverage-en/sessions/2027-04-15_05-30-00-quick/answers.jsonl +0 -0
  102. livedeck/sample_workspaces/niihama-beverage-en/sessions/2027-04-15_05-30-00-quick/raw_chunks.jsonl +10 -0
  103. livedeck/sample_workspaces/niihama-beverage-en/sessions/2027-04-15_05-30-00-quick/session.json +7 -0
  104. livedeck/sample_workspaces/niihama-beverage-en/sessions/2027-04-15_05-30-00-quick/speech_units.jsonl +10 -0
  105. livedeck/sample_workspaces/niihama-beverage-en/sessions/2027-04-15_05-30-00-quick/topics.jsonl +0 -0
  106. livedeck/sample_workspaces/niihama-beverage-en/tags.json +205 -0
  107. livedeck/sample_workspaces/niihama-beverage-en/workspace.json +8 -0
  108. livedeck/sample_workspaces/niihama-beverage-ja/cues/closing.md +3 -0
  109. livedeck/sample_workspaces/niihama-beverage-ja/cues/opening.md +3 -0
  110. livedeck/sample_workspaces/niihama-beverage-ja/cues/self_intro.md +9 -0
  111. livedeck/sample_workspaces/niihama-beverage-ja/documents/ES.md +7 -0
  112. livedeck/sample_workspaces/niihama-beverage-ja/documents//343/202/242/343/203/253/343/203/220/343/202/244/343/203/210/343/203/273/350/252/262/345/244/226/346/264/273/345/213/225/343/201/256/347/265/214/351/250/223/346/225/264/347/220/206.md +39 -0
  113. livedeck/sample_workspaces/niihama-beverage-ja/documents//343/202/274/343/203/237/343/203/273/345/215/222/350/253/226/343/203/241/343/203/242.md +17 -0
  114. livedeck/sample_workspaces/niihama-beverage-ja/documents//343/203/227/343/203/255/343/203/225/343/202/243/343/203/274/343/203/253/343/203/273/350/207/252/345/267/261/347/264/271/344/273/213/343/203/241/343/203/242.md +17 -0
  115. livedeck/sample_workspaces/niihama-beverage-ja/documents//344/274/201/346/245/255HP_/344/274/232/347/244/276/346/246/202/350/246/201/343/203/273/344/272/213/346/245/255/347/264/271/344/273/213.md +13 -0
  116. livedeck/sample_workspaces/niihama-beverage-ja/documents//345/213/237/351/233/206/350/246/201/351/240/205_/345/226/266/346/245/255/350/262/251/344/277/203/350/201/267.md +13 -0
  117. livedeck/sample_workspaces/niihama-beverage-ja/documents//345/213/244/345/213/231/346/235/241/344/273/266/343/203/273/351/201/270/350/200/203/347/212/266/346/263/201/343/203/241/343/203/242.md +14 -0
  118. livedeck/sample_workspaces/niihama-beverage-ja/documents//345/277/227/346/234/233/345/213/225/346/251/237/343/203/273/350/207/252/345/267/261/345/210/206/346/236/220/343/203/241/343/203/242.md +24 -0
  119. livedeck/sample_workspaces/niihama-beverage-ja/documents//350/252/254/346/230/216/344/274/232/343/203/273/344/274/201/346/245/255/347/240/224/347/251/266/343/203/241/343/203/242.md +14 -0
  120. livedeck/sample_workspaces/niihama-beverage-ja/records/index.json +806 -0
  121. livedeck/sample_workspaces/niihama-beverage-ja/sessions/2027-04-15_05-30-00-demo1/answers.jsonl +0 -0
  122. livedeck/sample_workspaces/niihama-beverage-ja/sessions/2027-04-15_05-30-00-demo1/raw_chunks.jsonl +84 -0
  123. livedeck/sample_workspaces/niihama-beverage-ja/sessions/2027-04-15_05-30-00-demo1/session.json +7 -0
  124. livedeck/sample_workspaces/niihama-beverage-ja/sessions/2027-04-15_05-30-00-demo1/speech_units.jsonl +84 -0
  125. livedeck/sample_workspaces/niihama-beverage-ja/sessions/2027-04-15_05-30-00-demo1/topics.jsonl +0 -0
  126. livedeck/sample_workspaces/niihama-beverage-ja/sessions/2027-04-15_05-30-00-quick/answers.jsonl +0 -0
  127. livedeck/sample_workspaces/niihama-beverage-ja/sessions/2027-04-15_05-30-00-quick/raw_chunks.jsonl +10 -0
  128. livedeck/sample_workspaces/niihama-beverage-ja/sessions/2027-04-15_05-30-00-quick/session.json +7 -0
  129. livedeck/sample_workspaces/niihama-beverage-ja/sessions/2027-04-15_05-30-00-quick/speech_units.jsonl +10 -0
  130. livedeck/sample_workspaces/niihama-beverage-ja/sessions/2027-04-15_05-30-00-quick/topics.jsonl +0 -0
  131. livedeck/sample_workspaces/niihama-beverage-ja/tags.json +205 -0
  132. livedeck/sample_workspaces/niihama-beverage-ja/tts_pronunciation.json +14 -0
  133. livedeck/sample_workspaces/niihama-beverage-ja/workspace.json +8 -0
  134. livedeck/scheduler.py +294 -0
  135. livedeck/search.py +275 -0
  136. livedeck/secrets.py +101 -0
  137. livedeck/session.py +1074 -0
  138. livedeck/setup_wizard.py +886 -0
  139. livedeck/single_turn_intent_view.py +564 -0
  140. livedeck/single_turn_view.py +577 -0
  141. livedeck/stt/__init__.py +201 -0
  142. livedeck/stt/backends.py +154 -0
  143. livedeck/stt/segmenters.py +368 -0
  144. livedeck/stt_charts.py +367 -0
  145. livedeck/stt_client.py +331 -0
  146. livedeck/stt_engine.py +220 -0
  147. livedeck/stt_eval.py +1055 -0
  148. livedeck/stt_eval_view.py +1283 -0
  149. livedeck/stt_results.py +476 -0
  150. livedeck/stt_runtime.py +648 -0
  151. livedeck/stt_runtime_view.py +726 -0
  152. livedeck/stt_worker.py +653 -0
  153. livedeck/tag_editor.py +910 -0
  154. livedeck/taxonomy.py +410 -0
  155. livedeck/text_rules.py +281 -0
  156. livedeck/title_similarity.py +383 -0
  157. livedeck/transcript_layout.py +94 -0
  158. livedeck/transcript_topics.py +387 -0
  159. livedeck/transcript_view.py +923 -0
  160. livedeck/workspace.py +482 -0
  161. livedeck/workspace_view.py +2403 -0
  162. livedeck-0.1.0.dist-info/METADATA +212 -0
  163. livedeck-0.1.0.dist-info/RECORD +167 -0
  164. livedeck-0.1.0.dist-info/WHEEL +4 -0
  165. livedeck-0.1.0.dist-info/entry_points.txt +2 -0
  166. livedeck-0.1.0.dist-info/licenses/LICENSE +662 -0
  167. livedeck-0.1.0.dist-info/licenses/THIRD_PARTY_LICENSES.md +67 -0
livedeck/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Desktop interview assistance."""
livedeck/__main__.py ADDED
@@ -0,0 +1,111 @@
1
+ """Run the desktop app from its source checkout."""
2
+
3
+ import argparse
4
+ import logging
5
+ import os
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from PySide6.QtWidgets import QApplication
10
+
11
+ from .audio import create_audio_capture
12
+ from .gui import MainWindow
13
+ from .session import Session
14
+ from .stt_client import LocalSTT
15
+
16
+
17
+ def _has_fcitx_qt_plugin(plugin_dirs: tuple[Path, ...] | None = None) -> bool:
18
+ """Return True if a Qt6 fcitx/fcitx5 platforminputcontexts plugin exists in PySide6 or QT_PLUGIN_PATH."""
19
+ dirs: list[Path] = []
20
+ if plugin_dirs is not None:
21
+ dirs.extend(plugin_dirs)
22
+ else:
23
+ try:
24
+ import PySide6
25
+ dirs.append(Path(PySide6.__file__).resolve().parent / 'Qt' / 'plugins' / 'platforminputcontexts')
26
+ except Exception:
27
+ pass
28
+ for raw in os.environ.get('QT_PLUGIN_PATH', '').split(os.pathsep):
29
+ if raw:
30
+ dirs.append(Path(raw) / 'platforminputcontexts')
31
+ for d in dirs:
32
+ if d.is_dir() and any('fcitx' in p.name.lower() for p in d.glob('*.so')):
33
+ return True
34
+ return False
35
+
36
+
37
+ def _configure_wayland_ime(
38
+ env: dict[str, str] | None = None,
39
+ *,
40
+ platform: str | None = None,
41
+ has_fcitx_plugin: bool | None = None,
42
+ ) -> bool:
43
+ """Unset QT_IM_MODULE=fcitx on Linux Wayland when PySide6 lacks the fcitx plugin.
44
+
45
+ Qt6 on Wayland natively uses the Wayland text-input protocol (which Fcitx5 supports)
46
+ when QT_IM_MODULE is unset; leaving QT_IM_MODULE=fcitx without the bundled plugin
47
+ breaks Japanese IME input across all QLineEdit/QPlainTextEdit widgets.
48
+ """
49
+ target_env = os.environ if env is None else env
50
+ plat = sys.platform if platform is None else platform
51
+ if plat != 'linux':
52
+ return False
53
+ qpa = target_env.get('QT_QPA_PLATFORM', '').strip().lower()
54
+ if qpa and not qpa.startswith('wayland'):
55
+ return False
56
+ is_wayland = target_env.get('XDG_SESSION_TYPE', '').strip().lower() == 'wayland' or bool(
57
+ target_env.get('WAYLAND_DISPLAY', '').strip()
58
+ )
59
+ if not is_wayland:
60
+ return False
61
+ im = target_env.get('QT_IM_MODULE', '').strip().lower()
62
+ if im not in ('fcitx', 'fcitx5'):
63
+ return False
64
+ plugin_present = _has_fcitx_qt_plugin() if has_fcitx_plugin is None else has_fcitx_plugin
65
+ if plugin_present:
66
+ return False
67
+ target_env.pop('QT_IM_MODULE', None)
68
+ return True
69
+
70
+
71
+ def main():
72
+ # Frozen PyInstaller bundles invoke themselves with `--stt-worker` to spawn the STT subprocess.
73
+ if len(sys.argv) >= 2 and sys.argv[1] == '--stt-worker':
74
+ from .stt_worker import main as stt_worker_main
75
+ return stt_worker_main(sys.argv[2:])
76
+
77
+ logging.basicConfig(level=logging.INFO)
78
+ _configure_wayland_ime()
79
+ from .paths import TomlSettings, bundle_root, config_file
80
+ root = bundle_root()
81
+ parser = argparse.ArgumentParser(description=__doc__)
82
+ parser.add_argument('--workspace', type=Path)
83
+ parser.add_argument('--setup', action='store_true', help='Launch the guided setup wizard on startup.')
84
+ parser.add_argument('--smoke-test', action='store_true', help='Initialize MainWindow and exit (CI verification).')
85
+ args, qt_args = parser.parse_known_args()
86
+ app = QApplication([sys.argv[0], *qt_args])
87
+ from .i18n import set_language
88
+ from .setup_wizard import SetupWizard, needs_initial_setup
89
+
90
+ storage = TomlSettings(config_file())
91
+ set_language(str(storage.value('ui/language', 'auto') or 'auto'))
92
+ workspace_path = args.workspace
93
+ if not args.smoke_test and (args.setup or needs_initial_setup(storage)):
94
+ wizard = SetupWizard(storage)
95
+ wizard.exec()
96
+ if workspace_path is None and wizard.created_workspace_path is not None:
97
+ workspace_path = wizard.created_workspace_path
98
+ stt = LocalSTT(root)
99
+ capture = create_audio_capture(stt.audio, stt.flush)
100
+ session = Session(stt, capture)
101
+ window = MainWindow(session, workspace_path=workspace_path)
102
+ if args.smoke_test:
103
+ session.close()
104
+ return 0
105
+ app.aboutToQuit.connect(session.close)
106
+ window.show()
107
+ return app.exec()
108
+
109
+
110
+ if __name__ == "__main__":
111
+ raise SystemExit(main())
@@ -0,0 +1,135 @@
1
+ """Pluggable, interchangeable, and parallel-runnable mid-stage dialogue analyzers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from collections.abc import Callable, Sequence
7
+ from dataclasses import dataclass
8
+ from typing import TYPE_CHECKING, Protocol, runtime_checkable
9
+
10
+ from ..core import InterviewSettings
11
+ from ..llm import LLMConfig
12
+ from ..taxonomy import DEFAULT_TAG_REGISTRY, TagRegistry
13
+
14
+ if TYPE_CHECKING:
15
+ from ..dialogue import DialogueState, TurnAnalysis
16
+
17
+ DEFAULT_ANALYZER = 'llm_stateful_v1'
18
+
19
+
20
+ @dataclass(frozen=True, slots=True)
21
+ class AnalyzerSpec:
22
+ id: str
23
+ label: str
24
+ description: str
25
+ requires_llm: bool = True
26
+ timeout_s: float = 12.0
27
+
28
+
29
+ @runtime_checkable
30
+ class DialogueAnalyzer(Protocol):
31
+ spec: AnalyzerSpec
32
+
33
+ async def analyze(
34
+ self,
35
+ state: DialogueState,
36
+ settings: InterviewSettings,
37
+ *,
38
+ catalog: Sequence[str] = (),
39
+ glossary: Sequence[str] = (),
40
+ ) -> TurnAnalysis: ...
41
+
42
+
43
+ AnalyzerFactory = Callable[[LLMConfig | None, TagRegistry], DialogueAnalyzer]
44
+ _ANALYZER_REGISTRY: dict[str, tuple[AnalyzerSpec, AnalyzerFactory]] = {}
45
+
46
+
47
+ def register_analyzer(
48
+ spec: AnalyzerSpec,
49
+ factory: AnalyzerFactory,
50
+ *,
51
+ replace: bool = False,
52
+ ) -> None:
53
+ if not spec.id.strip():
54
+ raise ValueError('Analyzer ID must not be empty.')
55
+ if spec.id in _ANALYZER_REGISTRY and not replace:
56
+ raise ValueError(f'Duplicate analyzer ID: {spec.id}')
57
+ _ANALYZER_REGISTRY[spec.id] = (spec, factory)
58
+
59
+
60
+ def unregister_analyzer(analyzer_id: str) -> None:
61
+ _ANALYZER_REGISTRY.pop(analyzer_id, None)
62
+
63
+
64
+ def list_analyzers() -> tuple[AnalyzerSpec, ...]:
65
+ return tuple(spec for spec, _ in _ANALYZER_REGISTRY.values())
66
+
67
+
68
+ def get_analyzer_spec(analyzer_id: str) -> AnalyzerSpec:
69
+ if analyzer_id not in _ANALYZER_REGISTRY:
70
+ available = ', '.join(_ANALYZER_REGISTRY) or '(none)'
71
+ raise ValueError(f'Unknown analyzer: {analyzer_id} (available: {available})')
72
+ return _ANALYZER_REGISTRY[analyzer_id][0]
73
+
74
+
75
+ def build_analyzer(
76
+ analyzer_id: str = DEFAULT_ANALYZER,
77
+ config: LLMConfig | None = None,
78
+ *,
79
+ tags: TagRegistry | None = None,
80
+ ) -> DialogueAnalyzer:
81
+ spec, factory = _ANALYZER_REGISTRY.get(analyzer_id, (None, None))
82
+ if spec is None or factory is None:
83
+ raise ValueError(f'Unknown analyzer: {analyzer_id}')
84
+ if spec.requires_llm and config is None:
85
+ raise ValueError(f'Analyzer {analyzer_id} requires an LLM config.')
86
+ return factory(config, tags or DEFAULT_TAG_REGISTRY)
87
+
88
+
89
+ async def run_analyzers_parallel(
90
+ analyzer_ids: Sequence[str],
91
+ state: DialogueState,
92
+ settings: InterviewSettings,
93
+ config: LLMConfig | None = None,
94
+ *,
95
+ catalog: Sequence[str] = (),
96
+ glossary: Sequence[str] = (),
97
+ tags: TagRegistry | None = None,
98
+ ) -> dict[str, TurnAnalysis]:
99
+ """Run multiple interchangeable analyzers concurrently against independent clones of `state`."""
100
+ unique_ids = tuple(dict.fromkeys(analyzer_ids))
101
+
102
+ async def _one(aid: str) -> tuple[str, TurnAnalysis]:
103
+ analyzer = build_analyzer(aid, config, tags=tags)
104
+ return aid, await invoke_analyzer(analyzer, state.clone(), settings, catalog=catalog, glossary=glossary)
105
+
106
+ pairs = await asyncio.gather(*(_one(aid) for aid in unique_ids))
107
+ return dict(pairs)
108
+
109
+
110
+ async def invoke_analyzer(
111
+ analyzer: DialogueAnalyzer,
112
+ state: DialogueState,
113
+ settings: InterviewSettings,
114
+ *,
115
+ catalog: Sequence[str] = (),
116
+ glossary: Sequence[str] = (),
117
+ products: Sequence[tuple[str, str]] = (),
118
+ ) -> TurnAnalysis:
119
+ """Invoke `analyzer.analyze`, passing `glossary` only if accepted (backward compatible with custom fakes)."""
120
+ import inspect
121
+
122
+ if isinstance(analyzer, _llm_product_fidelity_v1.ProductFidelityAnalyzer):
123
+ return await analyzer.analyze(state, settings, catalog=catalog, glossary=glossary, products=products)
124
+ sig = inspect.signature(analyzer.analyze)
125
+ if 'glossary' in sig.parameters or any(
126
+ p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values()
127
+ ):
128
+ return await analyzer.analyze(state, settings, catalog=catalog, glossary=glossary)
129
+ return await analyzer.analyze(state, settings, catalog=catalog)
130
+
131
+
132
+ # Register built-in mid-stage analyzers on import.
133
+ from . import llm_stateful_v1 as _llm_stateful_v1 # noqa: E402, F401
134
+ from . import heuristic_offline as _heuristic_offline # noqa: E402, F401
135
+ from . import llm_product_fidelity_v1 as _llm_product_fidelity_v1 # noqa: E402, F401
@@ -0,0 +1,94 @@
1
+ """Deterministic offline mid-stage analyzer for unit tests, CI smoke checks, and baselines."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ import re
7
+
8
+ from ..core import InterviewSettings
9
+ from ..dialogue import AnalyzedPart, DialogueState, TurnAction, TurnAnalysis
10
+ from ..taxonomy import DEFAULT_TAG_REGISTRY, TagRegistry
11
+ from ..text_rules import has_question_cue
12
+ from . import AnalyzerSpec, register_analyzer
13
+
14
+ _CONNECTIVITY_RE = re.compile(r'(?:音声|映像|カメラ|マイク|聞こえ|届いて|映って).*(?:問題なく|大丈夫|聞こえ|届いて|映って)')
15
+ _CLOSING_RE = re.compile(r'(?:本日は|お時間になりました|ありがとうございました|失礼いたします).*(?:ありがとう|ご案内|ご連絡|頑張ってください)')
16
+
17
+ HEURISTIC_ANALYZER_SPEC = AnalyzerSpec(
18
+ id='heuristic_offline',
19
+ label='Offline Heuristic Analyzer (test/CI)',
20
+ description='Lightweight offline baseline that classifies wait/continue/shift and merges pending utterances without an LLM.',
21
+ requires_llm=False,
22
+ timeout_s=2.0,
23
+ )
24
+
25
+
26
+ class HeuristicDialogueAnalyzer:
27
+ """Deterministic offline analyzer for unit tests, CI smoke checks, and ablation baselines."""
28
+
29
+ spec = HEURISTIC_ANALYZER_SPEC
30
+
31
+ def __init__(self, tags: TagRegistry = DEFAULT_TAG_REGISTRY) -> None:
32
+ self.tags = tags
33
+
34
+ async def analyze(
35
+ self,
36
+ state: DialogueState,
37
+ settings: InterviewSettings,
38
+ *,
39
+ catalog: Sequence[str] = (),
40
+ glossary: Sequence[str] = (),
41
+ ) -> TurnAnalysis:
42
+ del settings, catalog, glossary
43
+ pending = state.pending_interviewer_units()
44
+ if not pending:
45
+ return TurnAnalysis(action=TurnAction.WAIT)
46
+ latest_text = pending[-1].text.strip()
47
+ if pending[-1].backchannel:
48
+ return TurnAnalysis(action=TurnAction.WAIT)
49
+ if _CONNECTIVITY_RE.search(latest_text) and '自己紹介' not in latest_text:
50
+ action = TurnAction.CONTINUE if state.active_topic is not None else TurnAction.SHIFT
51
+ return TurnAnalysis(
52
+ action=action,
53
+ topic_label='' if action == TurnAction.CONTINUE else '挨拶・接続確認',
54
+ resolved_question='',
55
+ parts=(AnalyzedPart('no_action'),),
56
+ utterance_ids=tuple(u.unit_id for u in pending),
57
+ )
58
+ if _CLOSING_RE.search(latest_text):
59
+ return TurnAnalysis(
60
+ action=TurnAction.SHIFT,
61
+ topic_label='クロージング',
62
+ resolved_question=latest_text,
63
+ parts=(AnalyzedPart('closing'),),
64
+ utterance_ids=tuple(u.unit_id for u in pending),
65
+ )
66
+ if not has_question_cue(latest_text):
67
+ return TurnAnalysis(action=TurnAction.WAIT)
68
+
69
+ combined = '\n'.join(u.text.strip() for u in pending)
70
+ intent = 'experience'
71
+ if '自己紹介' in combined:
72
+ intent = 'self_intro'
73
+ elif any(k in combined for k in ('聞いておきたいこと', '聞きたいこと', '質問はありますか')):
74
+ intent = 'reverse_question'
75
+ elif any(k in combined for k in ('通われて', '免許', '運転', '転勤', '一人暮らし', 'ほかにどんな業界')):
76
+ intent = 'logistics'
77
+ elif any(k in combined for k in ('志望', 'メーカーの営業', 'イメージされて')):
78
+ intent = 'motivation'
79
+
80
+ active = state.active_topic
81
+ is_same_topic = active is not None and intent in active.intents and any(
82
+ k in latest_text for k in ('ちなみに', 'あと', 'それ', 'その')
83
+ )
84
+ action = TurnAction.CONTINUE if is_same_topic else TurnAction.SHIFT
85
+ return TurnAnalysis(
86
+ action=action,
87
+ topic_label=active.label if (action == TurnAction.CONTINUE and active is not None) else intent,
88
+ resolved_question=combined,
89
+ parts=(AnalyzedPart(intent),),
90
+ utterance_ids=tuple(u.unit_id for u in pending),
91
+ )
92
+
93
+
94
+ register_analyzer(HEURISTIC_ANALYZER_SPEC, lambda _config, tags: HeuristicDialogueAnalyzer(tags))
@@ -0,0 +1,138 @@
1
+ """Workspace-scoped product spelling adjudication after the stateful analyzer."""
2
+
3
+ from dataclasses import dataclass, replace
4
+ from difflib import SequenceMatcher
5
+ from functools import lru_cache
6
+ import re
7
+ import unicodedata
8
+
9
+ from ..core import InterviewSettings
10
+ from ..dialogue import DialogueState, TurnAnalysis
11
+ from ..i18n import load_prompt
12
+ from ..llm import LLMError
13
+ from . import AnalyzerSpec, register_analyzer
14
+ from .llm_stateful_v1 import LLMDialogueAnalyzer
15
+
16
+
17
+ def _key(text: str) -> str:
18
+ text = unicodedata.normalize('NFKC', text).casefold()
19
+ return ''.join(chr(ord(c) + 96) if 'ぁ' <= c <= 'ゖ' else c for c in text if not c.isspace())
20
+
21
+
22
+ @lru_cache(maxsize=1)
23
+ def _tokenizer():
24
+ try:
25
+ from janome.tokenizer import Tokenizer
26
+ except ImportError:
27
+ return None
28
+ return Tokenizer()
29
+
30
+
31
+ def _tokens(text):
32
+ tokenizer = _tokenizer()
33
+ if tokenizer is None:
34
+ for m in re.finditer(r'[ァ-ヺー]+|[ぁ-ゖ]+|[一-龯々]+|[a-zA-Z0-9]+|\S', text):
35
+ yield m.start(), m.end(), _key(m[0])
36
+ return
37
+ cursor = 0
38
+ for token in tokenizer.tokenize(text):
39
+ start = text.find(token.surface, cursor)
40
+ if start < 0:
41
+ break
42
+ cursor = start + len(token.surface)
43
+ yield start, cursor, _key(token.surface if token.reading == '*' else token.reading)
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class _Option:
48
+ start: int
49
+ end: int
50
+ source: str
51
+ name: str
52
+
53
+
54
+ @lru_cache(maxsize=512)
55
+ def _product_keys(name, reading):
56
+ forms = (name, reading)
57
+ return frozenset(key for form in forms for key in (
58
+ _key(form), ''.join(k for _, _, k in _tokens(form))
59
+ ) if len(key) >= 3)
60
+
61
+
62
+ def _options(question, pending, products):
63
+ tokens = list(_tokens(question))
64
+ protected = [(m.start(), m.end()) for name, _ in products
65
+ for m in re.finditer(re.escape(name), question)]
66
+ ranked = []
67
+ for i, (start, _, _) in enumerate(tokens):
68
+ reading = ''
69
+ for _, end, token_key in tokens[i:i + 10]:
70
+ if not token_key:
71
+ continue
72
+ if not token_key.isalnum():
73
+ break
74
+ reading += token_key
75
+ source = question[start:end]
76
+ if any(start < b and end > a for a, b in protected):
77
+ break
78
+ if not any(source in text for text in pending):
79
+ continue
80
+ for name, keys in products:
81
+ score = max((_similarity(k, reading) for k in keys), default=0)
82
+ if score >= 0.84:
83
+ ranked.append((score, _Option(start, end, source, name)))
84
+ # One best span per overlapping region per target. Do not automatically apply even exact readings.
85
+ kept = []
86
+ for _, option in sorted(ranked, key=lambda pair: (-pair[0], -len(pair[1].source))):
87
+ if not any(o.name == option.name and o.start < option.end and o.end > option.start for o in kept):
88
+ kept.append(option)
89
+ return kept[:16]
90
+
91
+
92
+ def _similarity(target, reading):
93
+ if target == reading:
94
+ return 1
95
+ if min(len(target), len(reading)) < 5 or abs(len(target) - len(reading)) > 2:
96
+ return 0
97
+ return SequenceMatcher(None, target, reading, autojunk=False).ratio()
98
+
99
+
100
+ class ProductFidelityAnalyzer(LLMDialogueAnalyzer):
101
+ spec = AnalyzerSpec(id='llm_product_fidelity_v1', label='LLM Stateful Analyzer (product fidelity)',
102
+ description='Adjudicates workspace product spelling candidates in resolved questions using conversation context.')
103
+
104
+ async def analyze(self, state: DialogueState, settings: InterviewSettings, *, catalog=(), glossary=(), products=()) -> TurnAnalysis:
105
+ base = await super().analyze(state, settings, catalog=catalog, glossary=glossary)
106
+ q = base.resolved_question
107
+ if not q or not products:
108
+ return base
109
+ pending = [u.text for u in state.pending_interviewer_units()]
110
+ options = _options(q, pending, [(n, _product_keys(n, r)) for n, r in products])
111
+ if not options:
112
+ return base
113
+ schema = {'name': 'product_spelling_choices', 'strict': True, 'schema': {
114
+ 'type': 'object', 'additionalProperties': False, 'required': ['choices'], 'properties': {
115
+ 'choices': {'type': 'array', 'items': {'type': 'integer', 'enum': list(range(len(options)))}}}}}
116
+ payload = {'recent_dialogue': [{'speaker': u.speaker.value, 'text': u.text}
117
+ for u in state.units[-8:]], 'resolved_question': q,
118
+ 'candidates': [{'index': i, 'start': o.start, 'source': o.source, 'product_name': o.name}
119
+ for i, o in enumerate(options)]}
120
+ try:
121
+ reply = await self._complete(load_prompt('product_fidelity_v1'), payload, schema)
122
+ except LLMError:
123
+ return base
124
+ ids = reply.get('choices') if isinstance(reply, dict) else None
125
+ if not isinstance(ids, list) or any(type(i) is not int or not 0 <= i < len(options) for i in ids):
126
+ return base
127
+ if not ids:
128
+ return base
129
+ boundary = len(q)
130
+ for o in sorted((options[i] for i in ids), key=lambda o: -o.start):
131
+ if o.end > boundary:
132
+ return base
133
+ q = q[:o.start] + o.name + q[o.end:]
134
+ boundary = o.start
135
+ return replace(base, resolved_question=q)
136
+
137
+
138
+ register_analyzer(ProductFidelityAnalyzer.spec, ProductFidelityAnalyzer)
@@ -0,0 +1,152 @@
1
+ """Stateful LLM mid-stage dialogue analyzer v1 (two-layer topic + intent unification)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ import json
7
+
8
+ import httpcore # noqa: F401 - avoid lazy import stall inside QThread workers
9
+ import httpx
10
+ from openai import APIError, AsyncOpenAI, DefaultAsyncHttpxClient
11
+
12
+ from ..core import InterviewSettings
13
+ from ..dialogue import DialogueState, TurnAction, TurnAnalysis, _normalize_analysis
14
+ from ..i18n import load_prompt
15
+ from ..llm import LLMConfig, LLMError, chat_create_with_thinking_fallback
16
+ from ..taxonomy import DEFAULT_TAG_REGISTRY, TagRegistry
17
+ from . import AnalyzerSpec, register_analyzer
18
+
19
+
20
+ def _build_llm_instructions(tags: TagRegistry, *, lang: str | None = None) -> str:
21
+ return load_prompt('analyzer_v1', lang=lang).replace('{tag_rules}', tags.render_prompt_rules())
22
+
23
+
24
+ def _build_llm_schema(tags: TagRegistry) -> dict:
25
+ return {
26
+ 'name': 'dialogue_turn_analysis',
27
+ 'strict': True,
28
+ 'schema': {
29
+ 'type': 'object',
30
+ 'additionalProperties': False,
31
+ 'required': ['action', 'topic_label', 'resolved_question', 'shift_start_unit_id', 'parts'],
32
+ 'properties': {
33
+ 'action': {'type': 'string', 'enum': [a.value for a in TurnAction]},
34
+ 'topic_label': {'type': 'string'},
35
+ 'resolved_question': {'type': 'string'},
36
+ 'shift_start_unit_id': {'type': 'string'},
37
+ 'parts': {
38
+ 'type': 'array',
39
+ 'minItems': 0,
40
+ 'maxItems': 4,
41
+ 'items': {
42
+ 'type': 'object',
43
+ 'additionalProperties': False,
44
+ 'required': ['intent', 'question'],
45
+ 'properties': {
46
+ 'intent': {'type': 'string', 'enum': list(tags.tag_ids())},
47
+ 'question': {'type': 'string'},
48
+ },
49
+ },
50
+ },
51
+ },
52
+ },
53
+ }
54
+
55
+
56
+ LLM_ANALYZER_SPEC = AnalyzerSpec(
57
+ id='llm_stateful_v1',
58
+ label='LLM Stateful Analyzer v1 (topic + intent)',
59
+ description='Performs backchannel merging, wait/continue/shift classification, topic tagging, and intent classification in one structured JSON call.',
60
+ requires_llm=True,
61
+ timeout_s=12.0,
62
+ )
63
+
64
+
65
+ class LLMDialogueAnalyzer:
66
+ spec = LLM_ANALYZER_SPEC
67
+
68
+ def __init__(self, config: LLMConfig, tags: TagRegistry = DEFAULT_TAG_REGISTRY) -> None:
69
+ self.config = config
70
+ self.tags = tags
71
+
72
+ def _instructions(self) -> str:
73
+ return _build_llm_instructions(self.tags)
74
+
75
+ async def analyze(
76
+ self,
77
+ state: DialogueState,
78
+ settings: InterviewSettings,
79
+ *,
80
+ catalog: Sequence[str] = (),
81
+ glossary: Sequence[str] = (),
82
+ ) -> TurnAnalysis:
83
+ del settings, glossary
84
+ pending = state.pending_interviewer_units()
85
+ if not pending:
86
+ return TurnAnalysis(action=TurnAction.WAIT)
87
+ latest = pending[-1]
88
+ if latest.backchannel:
89
+ return TurnAnalysis(action=TurnAction.WAIT)
90
+
91
+ active = state.active_topic
92
+ recent = [
93
+ {'id': unit.unit_id, 'speaker': unit.speaker.value, 'text': unit.text}
94
+ for unit in state.units[-8:]
95
+ ]
96
+ pending_payload = [
97
+ {'id': unit.unit_id, 'text': unit.text}
98
+ for unit in pending
99
+ ]
100
+ payload = {
101
+ 'active_topic': None if active is None else {
102
+ 'topic_id': active.topic_id,
103
+ 'label': active.label,
104
+ 'intents': list(active.intents),
105
+ 'previous_question': active.resolved_question,
106
+ },
107
+ 'recent_dialogue': recent,
108
+ 'pending_interviewer_utterances': pending_payload,
109
+ }
110
+ if catalog:
111
+ payload['topic_catalog'] = list(catalog[:48])
112
+ try:
113
+ raw = await self._complete(self._instructions(), payload, _build_llm_schema(self.tags))
114
+ return _normalize_analysis(
115
+ raw,
116
+ pending_ids=tuple(unit.unit_id for unit in pending),
117
+ pending_text='\n'.join(unit.text for unit in pending),
118
+ pending_texts=tuple(unit.text for unit in pending),
119
+ has_active_topic=active is not None,
120
+ tags=self.tags,
121
+ active_topic_intents=() if active is None else active.intents,
122
+ )
123
+ except (ValueError, TypeError, AttributeError, KeyError, IndexError):
124
+ raise LLMError('Failed to analyze dialogue state.') from None
125
+
126
+ async def _complete(self, instructions: str, payload: dict, schema: dict) -> dict:
127
+ try:
128
+ async with AsyncOpenAI(
129
+ base_url=self.config.base_url,
130
+ api_key=self.config.api_key or 'EMPTY',
131
+ max_retries=0,
132
+ timeout=min(self.spec.timeout_s, self.config.timeout_s),
133
+ http_client=DefaultAsyncHttpxClient(follow_redirects=False),
134
+ ) as client:
135
+ result = await chat_create_with_thinking_fallback(
136
+ client,
137
+ self.config,
138
+ model=self.config.model,
139
+ temperature=self.config.analyzer_temperature,
140
+ max_tokens=300,
141
+ response_format={'type': 'json_schema', 'json_schema': schema},
142
+ messages=[
143
+ {'role': 'system', 'content': instructions},
144
+ {'role': 'user', 'content': json.dumps(payload, ensure_ascii=False)},
145
+ ],
146
+ )
147
+ return json.loads(result.choices[0].message.content)
148
+ except (APIError, httpx.HTTPError, ValueError, TypeError, AttributeError, KeyError, IndexError):
149
+ raise LLMError('Failed to analyze dialogue state.') from None
150
+
151
+
152
+ register_analyzer(LLM_ANALYZER_SPEC, lambda config, tags: LLMDialogueAnalyzer(config, tags))