Spaces:
Running
Running
update ->add llm
Browse files- .env +18 -0
- .gitignore +1 -0
- README.md +79 -5
- db.py +136 -27
- docs/class_diagram.md +64 -7
- llm_client/__init__.py +23 -0
- llm_client/client.py +217 -0
- llm_client/config.py +123 -0
- llm_client/pipeline.py +211 -0
- llm_client/prompts.py +163 -0
- llm_client/schemas.py +115 -0
- main.py +239 -25
- requirements.txt +6 -0
- static/app.js +84 -9
- static/index.html +15 -0
- static/records.html +24 -0
- static/records.js +59 -2
- tests/test_llm_track.py +139 -0
- tests/test_main_llm_integration.py +276 -0
- tests/test_v8_integration.py +218 -0
.env
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
GEMINI_API_KEY=${gemini_api}
|
| 2 |
+
# ANTHROPIC_API_KEY=sk-ant-...
|
| 3 |
+
# OPENAI_API_KEY=sk-...
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
LLM_PROVIDER=google
|
| 7 |
+
|
| 8 |
+
GEMINI_MODEL=gemini-flash-latest
|
| 9 |
+
ANTHROPIC_MODEL=claude-sonnet-5
|
| 10 |
+
OPENAI_MODEL=gpt-4o-mini
|
| 11 |
+
|
| 12 |
+
# pre_pseudonymized = PII se odstraní lokálně (BERT/Presidio)
|
| 13 |
+
LLM_MODE=pre_pseudonymized
|
| 14 |
+
# Odeslání nemaskovaného textu je nutné povolit vědomě
|
| 15 |
+
LLM_ALLOW_RAW=false
|
| 16 |
+
|
| 17 |
+
# maximální počet souběžných požadavků při dávkovém zpracování (/ingest)
|
| 18 |
+
LLM_CONCURRENCY=4
|
.gitignore
CHANGED
|
@@ -3,3 +3,4 @@ __pycache__/
|
|
| 3 |
*.db
|
| 4 |
.cache/
|
| 5 |
.venv/
|
|
|
|
|
|
| 3 |
*.db
|
| 4 |
.cache/
|
| 5 |
.venv/
|
| 6 |
+
.env
|
README.md
CHANGED
|
@@ -27,6 +27,7 @@ version is tagged so the progression is visible in the git history.
|
|
| 27 |
| V5 | `v5.0` | Per-step model choice (sentiment, NER, topics) switched from radio buttons to a `<select>` dropdown; a free-text field for a custom model appears only when "Custom model" is selected. |
|
| 28 |
| V6 | `v6.0` | Batched inference for `/ingest`: NER, topic classification and sentiment analysis each run once over the whole batch instead of once per message, significantly reducing total processing time for large batches (especially on CPU-only hosting). |
|
| 29 |
| V7 | `v7.0` | `/ingest` runs as a background job instead of one long blocking request; the dashboard polls job status and shows a progress bar and elapsed-time timer. |
|
|
|
|
| 30 |
|
| 31 |
See [`docs/class_diagram.md`](docs/class_diagram.md) for the current architecture.
|
| 32 |
|
|
@@ -51,12 +52,13 @@ ingest → NER → topic classification → sentiment → anonymization → stor
|
|
| 51 |
| GET | `/` | Web dashboard |
|
| 52 |
| GET | `/health` | Service + model status |
|
| 53 |
| GET | `/models` | Default, suggested and currently cached models, per pipeline step |
|
| 54 |
-
|
|
| 55 |
-
| POST | `/
|
| 56 |
-
| POST | `/
|
|
|
|
| 57 |
| GET | `/ingest/status/{job_id}` | Progress (and, once done, the result) of a background ingest job |
|
| 58 |
-
| GET | `/records` | Recent stored (anonymized) records |
|
| 59 |
-
| GET | `/records/export` | Stored records exported as XML, JSON or CSV (`?format=`) |
|
| 60 |
| GET | `/stats` | Aggregate statistics (includes the list of supported export formats) |
|
| 61 |
|
| 62 |
### Example
|
|
@@ -174,6 +176,64 @@ timer (updated every 100ms from the browser's own clock, so it stays smooth
|
|
| 174 |
between polls). When the job reaches `done` or `error`, polling stops and
|
| 175 |
the final summary/error is shown, same as the old synchronous response.
|
| 176 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
## Data protection
|
| 178 |
|
| 179 |
The original message text is **never stored in readable form**. Only a SHA-256
|
|
@@ -194,3 +254,17 @@ uvicorn main:app --reload --port 8000
|
|
| 194 |
`requirements-dev.txt` holds extra dependencies (`pandas`, `seqeval`) needed
|
| 195 |
only by the offline helper scripts `prepare_dataset.py` and `evaluate.py` -
|
| 196 |
not required to run the API itself.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
| V5 | `v5.0` | Per-step model choice (sentiment, NER, topics) switched from radio buttons to a `<select>` dropdown; a free-text field for a custom model appears only when "Custom model" is selected. |
|
| 28 |
| V6 | `v6.0` | Batched inference for `/ingest`: NER, topic classification and sentiment analysis each run once over the whole batch instead of once per message, significantly reducing total processing time for large batches (especially on CPU-only hosting). |
|
| 29 |
| V7 | `v7.0` | `/ingest` runs as a background job instead of one long blocking request; the dashboard polls job status and shows a progress bar and elapsed-time timer. |
|
| 30 |
+
| V8 | `v8.0` | Optional LLM engine (Claude / Gemini / OpenAI) alongside the local BERT pipeline, selectable per request for both `/analyze` and `/ingest`; local pseudonymization always runs before any text reaches an LLM provider; results from both engines are stored and shown together in the same records list. |
|
| 31 |
|
| 32 |
See [`docs/class_diagram.md`](docs/class_diagram.md) for the current architecture.
|
| 33 |
|
|
|
|
| 52 |
| GET | `/` | Web dashboard |
|
| 53 |
| GET | `/health` | Service + model status |
|
| 54 |
| GET | `/models` | Default, suggested and currently cached models, per pipeline step |
|
| 55 |
+
| GET | `/engines` | Local pipeline + configured LLM providers, with availability (V8) |
|
| 56 |
+
| POST | `/analyze` | Full pipeline on a single message (`engine`: `local` or a provider id, V8) |
|
| 57 |
+
| POST | `/predict` | Sentiment only (backward compatible, local models only) |
|
| 58 |
+
| POST | `/ingest` | Start a background batch-ingest job for a CSV/JSON file, returns a `job_id` (`engine` field, V8) |
|
| 59 |
| GET | `/ingest/status/{job_id}` | Progress (and, once done, the result) of a background ingest job |
|
| 60 |
+
| GET | `/records` | Recent stored (anonymized) records, local and LLM engine alike; optional `?engine=local\|llm`, `?topic=`, `?sentiment=` filters (V8) |
|
| 61 |
+
| GET | `/records/export` | Stored records exported as XML, JSON or CSV (`?format=`), same optional filters (V8) |
|
| 62 |
| GET | `/stats` | Aggregate statistics (includes the list of supported export formats) |
|
| 63 |
|
| 64 |
### Example
|
|
|
|
| 176 |
between polls). When the job reaches `done` or `error`, polling stops and
|
| 177 |
the final summary/error is shown, same as the old synchronous response.
|
| 178 |
|
| 179 |
+
## Optional LLM engine (Claude / Gemini / OpenAI)
|
| 180 |
+
|
| 181 |
+
Since V8, each of the three tasks - sentiment, NER, topic classification -
|
| 182 |
+
can also be resolved by a single call to a large language model instead of
|
| 183 |
+
the local BERT pipeline. This is a second, independent "engine", not a
|
| 184 |
+
replacement: both are always available side by side, so results can be
|
| 185 |
+
compared.
|
| 186 |
+
|
| 187 |
+
| Engine | How | Package |
|
| 188 |
+
|--------|-----|---------|
|
| 189 |
+
| `local` (default `engine`) | The existing `pipeline.process_message`/`process_batch` (three separate models) | `processors/` |
|
| 190 |
+
| `google` (default LLM provider) | One Gemini call, structured output via `response_schema` | `llm_client/` |
|
| 191 |
+
| `anthropic` | One Claude call, structured output via tool use - optional, if the user has their own key | `llm_client/` |
|
| 192 |
+
| `openai` | One GPT call, structured output via JSON schema - optional, if the user has their own key | `llm_client/` |
|
| 193 |
+
|
| 194 |
+
`local` is the request-level default when `engine` is omitted (unchanged
|
| 195 |
+
behavior); among the LLM providers, `google` (Gemini) is the
|
| 196 |
+
`LLM_PROVIDER` default (`llm_client/config.py`) since it has a usable free
|
| 197 |
+
tier - Claude and OpenAI are additional choices for a user who has their
|
| 198 |
+
own API key for those.
|
| 199 |
+
|
| 200 |
+
`GET /engines` reports which providers are actually usable (an API key is
|
| 201 |
+
configured); the dashboard's **Engine** dropdown disables the rest instead
|
| 202 |
+
of hiding them, so it's clear what a full deployment would offer.
|
| 203 |
+
|
| 204 |
+
**Anonymization always happens locally, first.** Regardless of which engine
|
| 205 |
+
is chosen, the same `processors.anonymizer` pseudonymizes the message before
|
| 206 |
+
anything leaves the server; for an LLM engine, only the pseudonymized text
|
| 207 |
+
is sent to the provider's API (`llm_client.pipeline.LLMPipeline`, mode
|
| 208 |
+
`pre_pseudonymized`). The provider never sees the raw message. A raw-text
|
| 209 |
+
mode exists in `llm_client` for controlled experiments but requires an
|
| 210 |
+
explicit `LLM_ALLOW_RAW=1` opt-in and is not exposed through the API.
|
| 211 |
+
|
| 212 |
+
`POST /analyze` and `POST /ingest` both accept an `engine` field
|
| 213 |
+
(`"local"` by default) and, for LLM engines, an optional `llm_mode`. The
|
| 214 |
+
local-engine response shape is unchanged; the LLM-engine response adds
|
| 215 |
+
`engine`, `provider`, `model`, `latency_ms` and `cost_usd` on top of the
|
| 216 |
+
same `sentiment`/`topic`/`entities`/`anonymized_text` fields. `/ingest`
|
| 217 |
+
with an LLM engine uses the same background-job/progress mechanism from V7
|
| 218 |
+
(`GET /ingest/status/{job_id}`); the batch is processed with bounded
|
| 219 |
+
concurrency (`LLMPipeline.analyze_batch`, `LLM_CONCURRENCY` workers).
|
| 220 |
+
|
| 221 |
+
**Both engines store into the same place.** LLM results are mapped onto the
|
| 222 |
+
same shape the local pipeline already returns and saved via the same
|
| 223 |
+
`db.save_record` into the same `records` table (`db.py`), tagged with
|
| 224 |
+
`engine`/`provider`/`model`/`latency_ms`/`cost_usd` (`NULL` for local-engine
|
| 225 |
+
records). They therefore show up together in `GET /records`, the
|
| 226 |
+
`/records.html` dashboard (with an added **Engine** column and filter
|
| 227 |
+
dropdowns for **Engine**, **Topic** and **Sentiment**) and every export
|
| 228 |
+
format - `/records` and `/records/export` both accept optional
|
| 229 |
+
`?engine=local|llm`, `?topic=` and `?sentiment=` query params, usable
|
| 230 |
+
together, to narrow the list down - instead of living in a separate
|
| 231 |
+
database only reachable through a dedicated comparison view. A systematic
|
| 232 |
+
BERT-vs-LLM comparison
|
| 233 |
+
(agreement, entity-level P/R/F1, PII leak rate, latency/cost) was
|
| 234 |
+
originally planned as an automated dashboard here, but that comparison is
|
| 235 |
+
instead run manually and written up directly in the accompanying thesis.
|
| 236 |
+
|
| 237 |
## Data protection
|
| 238 |
|
| 239 |
The original message text is **never stored in readable form**. Only a SHA-256
|
|
|
|
| 254 |
`requirements-dev.txt` holds extra dependencies (`pandas`, `seqeval`) needed
|
| 255 |
only by the offline helper scripts `prepare_dataset.py` and `evaluate.py` -
|
| 256 |
not required to run the API itself.
|
| 257 |
+
|
| 258 |
+
The LLM engines are entirely optional: without any provider API key set,
|
| 259 |
+
the app runs exactly as before (`local` engine only). To enable one or more
|
| 260 |
+
providers, copy `.env.example` to `.env` and set `GEMINI_API_KEY` (the
|
| 261 |
+
default provider - has a usable free tier) and/or, if you have your own key
|
| 262 |
+
for them, `ANTHROPIC_API_KEY` and `OPENAI_API_KEY`; see
|
| 263 |
+
[`APPLY_V8.md`](APPLY_V8.md) for how to apply this version on top of an
|
| 264 |
+
existing V7 checkout.
|
| 265 |
+
|
| 266 |
+
## Future work
|
| 267 |
+
|
| 268 |
+
SQLite (used here for both engines' results) is a placeholder for local
|
| 269 |
+
development and Hugging Face Spaces hosting. A move to a self-hosted
|
| 270 |
+
deployment with MongoDB is planned but out of scope for this version.
|
db.py
CHANGED
|
@@ -69,6 +69,23 @@ def _get_connection() -> sqlite3.Connection:
|
|
| 69 |
)
|
| 70 |
"""
|
| 71 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
conn.commit()
|
| 73 |
return conn
|
| 74 |
|
|
@@ -85,6 +102,14 @@ def save_record(result: dict[str, Any], source: str = "single") -> None:
|
|
| 85 |
Persist one pipeline result. The original text is hashed (not stored);
|
| 86 |
the anonymized text is stored. If the result does not already contain an
|
| 87 |
anonymized text, it is anonymized here as a safeguard.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
"""
|
| 89 |
original_text = result.get("text", "") or ""
|
| 90 |
anonymized = result.get("anonymized_text") or anonymizer.anonymize_text(original_text)
|
|
@@ -98,8 +123,9 @@ def save_record(result: dict[str, Any], source: str = "single") -> None:
|
|
| 98 |
INSERT INTO records (
|
| 99 |
created_at, original_hash, anonymized_text, entities,
|
| 100 |
topic, topic_score, sentiment, sentiment_score,
|
| 101 |
-
conversation_id, source
|
| 102 |
-
|
|
|
|
| 103 |
""",
|
| 104 |
(
|
| 105 |
_utcnow(),
|
|
@@ -112,25 +138,70 @@ def save_record(result: dict[str, Any], source: str = "single") -> None:
|
|
| 112 |
result.get("sentiment_score"),
|
| 113 |
result.get("conversation_id"),
|
| 114 |
source,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
),
|
| 116 |
)
|
| 117 |
_db_conn.commit()
|
| 118 |
|
| 119 |
|
| 120 |
-
def
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
with _db_lock:
|
| 123 |
-
cur = _db_conn.execute(
|
| 124 |
-
"""
|
| 125 |
-
SELECT id, created_at, anonymized_text, entities,
|
| 126 |
-
topic, topic_score, sentiment, sentiment_score,
|
| 127 |
-
conversation_id, source
|
| 128 |
-
FROM records
|
| 129 |
-
ORDER BY id DESC
|
| 130 |
-
LIMIT ?
|
| 131 |
-
""",
|
| 132 |
-
(limit,),
|
| 133 |
-
)
|
| 134 |
rows = cur.fetchall()
|
| 135 |
|
| 136 |
records = []
|
|
@@ -151,6 +222,11 @@ def get_records(limit: int = 100) -> list[dict[str, Any]]:
|
|
| 151 |
"sentiment_score": r[7],
|
| 152 |
"conversation_id": r[8],
|
| 153 |
"source": r[9],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
}
|
| 155 |
)
|
| 156 |
return records
|
|
@@ -174,20 +250,25 @@ def stats() -> dict[str, Any]:
|
|
| 174 |
}
|
| 175 |
|
| 176 |
|
| 177 |
-
def _fetch_export_rows(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
"""Raw rows (most recent first) shared by every export format."""
|
| 179 |
-
|
|
|
|
| 180 |
SELECT id, created_at, anonymized_text, entities,
|
| 181 |
topic, topic_score, sentiment, sentiment_score,
|
| 182 |
-
conversation_id, source
|
| 183 |
-
|
|
|
|
| 184 |
ORDER BY id DESC
|
| 185 |
"""
|
| 186 |
if limit is not None:
|
| 187 |
query += " LIMIT ?"
|
| 188 |
-
params
|
| 189 |
-
else:
|
| 190 |
-
params = ()
|
| 191 |
|
| 192 |
with _db_lock:
|
| 193 |
return _db_conn.execute(query, params).fetchall()
|
|
@@ -216,6 +297,15 @@ def _export_xml(rows: list[tuple[Any, ...]]) -> bytes:
|
|
| 216 |
)
|
| 217 |
ET.SubElement(record_el, "conversation_id").text = r[8]
|
| 218 |
ET.SubElement(record_el, "source").text = r[9]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
entities_el = ET.SubElement(record_el, "entities")
|
| 221 |
for ent in _row_entities(r):
|
|
@@ -242,6 +332,11 @@ def _export_json(rows: list[tuple[Any, ...]]) -> bytes:
|
|
| 242 |
"sentiment_score": r[7],
|
| 243 |
"conversation_id": r[8],
|
| 244 |
"source": r[9],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
}
|
| 246 |
for r in rows
|
| 247 |
]
|
|
@@ -264,6 +359,11 @@ def _export_csv(rows: list[tuple[Any, ...]]) -> bytes:
|
|
| 264 |
"sentiment_score",
|
| 265 |
"conversation_id",
|
| 266 |
"source",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 267 |
"entities",
|
| 268 |
]
|
| 269 |
)
|
|
@@ -271,26 +371,35 @@ def _export_csv(rows: list[tuple[Any, ...]]) -> bytes:
|
|
| 271 |
entities_cell = "; ".join(
|
| 272 |
f"{ent.get('type', '')}:{ent.get('text', '')}" for ent in _row_entities(r)
|
| 273 |
)
|
| 274 |
-
writer.writerow(
|
|
|
|
|
|
|
| 275 |
|
| 276 |
# utf-8-sig (BOM) so Excel opens the file with correct encoding.
|
| 277 |
return buffer.getvalue().encode("utf-8-sig")
|
| 278 |
|
| 279 |
|
| 280 |
-
def export_records(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
"""
|
| 282 |
Export stored (anonymized) records in the given format.
|
| 283 |
|
| 284 |
Returns ``(content_bytes, media_type)``. Raises ``ValueError`` for an
|
| 285 |
unsupported ``fmt`` so the API layer can turn it into a clean 400
|
| 286 |
-
response. ``limit`` caps the number of most recent records exported
|
| 287 |
-
``None`` exports everything
|
|
|
|
| 288 |
"""
|
| 289 |
fmt = (fmt or "xml").strip().lower()
|
| 290 |
if fmt not in EXPORT_FORMATS:
|
| 291 |
supported = ", ".join(sorted(EXPORT_FORMATS))
|
| 292 |
raise ValueError(f"Unsupported export format '{fmt}'. Supported: {supported}.")
|
| 293 |
|
| 294 |
-
rows = _fetch_export_rows(limit)
|
| 295 |
exporter = {"xml": _export_xml, "json": _export_json, "csv": _export_csv}[fmt]
|
| 296 |
return exporter(rows), EXPORT_FORMATS[fmt]
|
|
|
|
| 69 |
)
|
| 70 |
"""
|
| 71 |
)
|
| 72 |
+
# Since V8: which engine produced the record ('local' or 'llm') and,
|
| 73 |
+
# for the LLM engine, which provider/model answered plus its latency and
|
| 74 |
+
# cost. Added via ALTER TABLE so existing conversation_logs.db files from
|
| 75 |
+
# earlier versions keep working; SQLite has no "ADD COLUMN IF NOT
|
| 76 |
+
# EXISTS", so a duplicate-column error on an already-migrated database
|
| 77 |
+
# is expected and ignored.
|
| 78 |
+
for column_def in (
|
| 79 |
+
"engine TEXT DEFAULT 'local'",
|
| 80 |
+
"provider TEXT",
|
| 81 |
+
"model TEXT",
|
| 82 |
+
"latency_ms INTEGER",
|
| 83 |
+
"cost_usd REAL",
|
| 84 |
+
):
|
| 85 |
+
try:
|
| 86 |
+
conn.execute(f"ALTER TABLE records ADD COLUMN {column_def}")
|
| 87 |
+
except sqlite3.OperationalError:
|
| 88 |
+
pass # column already exists
|
| 89 |
conn.commit()
|
| 90 |
return conn
|
| 91 |
|
|
|
|
| 102 |
Persist one pipeline result. The original text is hashed (not stored);
|
| 103 |
the anonymized text is stored. If the result does not already contain an
|
| 104 |
anonymized text, it is anonymized here as a safeguard.
|
| 105 |
+
|
| 106 |
+
Since V8, ``result`` may come from either engine: the local BERT
|
| 107 |
+
pipeline (no ``engine``/``provider`` keys - stored as ``engine="local"``,
|
| 108 |
+
``provider``/``model``/``latency_ms``/``cost_usd`` left ``NULL``) or the
|
| 109 |
+
LLM pipeline (``engine="llm"``, plus ``provider``, ``model``,
|
| 110 |
+
``latency_ms``, ``cost_usd``). Both land in the same ``records`` table
|
| 111 |
+
and are indistinguishable in the schema except for these columns, so the
|
| 112 |
+
dashboard can list and export them together.
|
| 113 |
"""
|
| 114 |
original_text = result.get("text", "") or ""
|
| 115 |
anonymized = result.get("anonymized_text") or anonymizer.anonymize_text(original_text)
|
|
|
|
| 123 |
INSERT INTO records (
|
| 124 |
created_at, original_hash, anonymized_text, entities,
|
| 125 |
topic, topic_score, sentiment, sentiment_score,
|
| 126 |
+
conversation_id, source,
|
| 127 |
+
engine, provider, model, latency_ms, cost_usd
|
| 128 |
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 129 |
""",
|
| 130 |
(
|
| 131 |
_utcnow(),
|
|
|
|
| 138 |
result.get("sentiment_score"),
|
| 139 |
result.get("conversation_id"),
|
| 140 |
source,
|
| 141 |
+
result.get("engine") or "local",
|
| 142 |
+
result.get("provider"),
|
| 143 |
+
result.get("model"),
|
| 144 |
+
result.get("latency_ms"),
|
| 145 |
+
result.get("cost_usd"),
|
| 146 |
),
|
| 147 |
)
|
| 148 |
_db_conn.commit()
|
| 149 |
|
| 150 |
|
| 151 |
+
def _build_filter(
|
| 152 |
+
engine: str | None = None,
|
| 153 |
+
topic: str | None = None,
|
| 154 |
+
sentiment: str | None = None,
|
| 155 |
+
) -> tuple[str, tuple[Any, ...]]:
|
| 156 |
+
"""
|
| 157 |
+
Shared ``WHERE`` clause for ``get_records``/``_fetch_export_rows``:
|
| 158 |
+
optionally narrow to one engine (``"local"`` | ``"llm"``), one topic, or
|
| 159 |
+
one sentiment label. Any combination may be used together; omitted
|
| 160 |
+
filters are simply not applied.
|
| 161 |
+
"""
|
| 162 |
+
conditions = []
|
| 163 |
+
params: tuple[Any, ...] = ()
|
| 164 |
+
if engine:
|
| 165 |
+
conditions.append("engine = ?")
|
| 166 |
+
params += (engine,)
|
| 167 |
+
if topic:
|
| 168 |
+
conditions.append("topic = ?")
|
| 169 |
+
params += (topic,)
|
| 170 |
+
if sentiment:
|
| 171 |
+
conditions.append("sentiment = ?")
|
| 172 |
+
params += (sentiment,)
|
| 173 |
+
clause = f" WHERE {' AND '.join(conditions)}" if conditions else ""
|
| 174 |
+
return clause, params
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def get_records(
|
| 178 |
+
limit: int = 100,
|
| 179 |
+
engine: str | None = None,
|
| 180 |
+
topic: str | None = None,
|
| 181 |
+
sentiment: str | None = None,
|
| 182 |
+
) -> list[dict[str, Any]]:
|
| 183 |
+
"""
|
| 184 |
+
Return the most recent records (anonymized only).
|
| 185 |
+
|
| 186 |
+
``engine`` optionally filters to ``"local"`` (BERT pipeline) or ``"llm"``
|
| 187 |
+
(any provider); ``topic``/``sentiment`` filter to an exact label. Any
|
| 188 |
+
combination of the three may be used together; omitted/``None`` means
|
| 189 |
+
"don't filter on this".
|
| 190 |
+
"""
|
| 191 |
+
where_clause, where_params = _build_filter(engine, topic, sentiment)
|
| 192 |
+
query = f"""
|
| 193 |
+
SELECT id, created_at, anonymized_text, entities,
|
| 194 |
+
topic, topic_score, sentiment, sentiment_score,
|
| 195 |
+
conversation_id, source,
|
| 196 |
+
engine, provider, model, latency_ms, cost_usd
|
| 197 |
+
FROM records{where_clause}
|
| 198 |
+
ORDER BY id DESC
|
| 199 |
+
LIMIT ?
|
| 200 |
+
"""
|
| 201 |
+
params = where_params + (limit,)
|
| 202 |
+
|
| 203 |
with _db_lock:
|
| 204 |
+
cur = _db_conn.execute(query, params)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
rows = cur.fetchall()
|
| 206 |
|
| 207 |
records = []
|
|
|
|
| 222 |
"sentiment_score": r[7],
|
| 223 |
"conversation_id": r[8],
|
| 224 |
"source": r[9],
|
| 225 |
+
"engine": r[10],
|
| 226 |
+
"provider": r[11],
|
| 227 |
+
"model": r[12],
|
| 228 |
+
"latency_ms": r[13],
|
| 229 |
+
"cost_usd": r[14],
|
| 230 |
}
|
| 231 |
)
|
| 232 |
return records
|
|
|
|
| 250 |
}
|
| 251 |
|
| 252 |
|
| 253 |
+
def _fetch_export_rows(
|
| 254 |
+
limit: int | None,
|
| 255 |
+
engine: str | None = None,
|
| 256 |
+
topic: str | None = None,
|
| 257 |
+
sentiment: str | None = None,
|
| 258 |
+
) -> list[tuple[Any, ...]]:
|
| 259 |
"""Raw rows (most recent first) shared by every export format."""
|
| 260 |
+
where_clause, params = _build_filter(engine, topic, sentiment)
|
| 261 |
+
query = f"""
|
| 262 |
SELECT id, created_at, anonymized_text, entities,
|
| 263 |
topic, topic_score, sentiment, sentiment_score,
|
| 264 |
+
conversation_id, source,
|
| 265 |
+
engine, provider, model, latency_ms, cost_usd
|
| 266 |
+
FROM records{where_clause}
|
| 267 |
ORDER BY id DESC
|
| 268 |
"""
|
| 269 |
if limit is not None:
|
| 270 |
query += " LIMIT ?"
|
| 271 |
+
params += (limit,)
|
|
|
|
|
|
|
| 272 |
|
| 273 |
with _db_lock:
|
| 274 |
return _db_conn.execute(query, params).fetchall()
|
|
|
|
| 297 |
)
|
| 298 |
ET.SubElement(record_el, "conversation_id").text = r[8]
|
| 299 |
ET.SubElement(record_el, "source").text = r[9]
|
| 300 |
+
ET.SubElement(record_el, "engine").text = r[10]
|
| 301 |
+
ET.SubElement(record_el, "provider").text = r[11]
|
| 302 |
+
ET.SubElement(record_el, "model").text = r[12]
|
| 303 |
+
ET.SubElement(record_el, "latency_ms").text = (
|
| 304 |
+
str(r[13]) if r[13] is not None else None
|
| 305 |
+
)
|
| 306 |
+
ET.SubElement(record_el, "cost_usd").text = (
|
| 307 |
+
str(r[14]) if r[14] is not None else None
|
| 308 |
+
)
|
| 309 |
|
| 310 |
entities_el = ET.SubElement(record_el, "entities")
|
| 311 |
for ent in _row_entities(r):
|
|
|
|
| 332 |
"sentiment_score": r[7],
|
| 333 |
"conversation_id": r[8],
|
| 334 |
"source": r[9],
|
| 335 |
+
"engine": r[10],
|
| 336 |
+
"provider": r[11],
|
| 337 |
+
"model": r[12],
|
| 338 |
+
"latency_ms": r[13],
|
| 339 |
+
"cost_usd": r[14],
|
| 340 |
}
|
| 341 |
for r in rows
|
| 342 |
]
|
|
|
|
| 359 |
"sentiment_score",
|
| 360 |
"conversation_id",
|
| 361 |
"source",
|
| 362 |
+
"engine",
|
| 363 |
+
"provider",
|
| 364 |
+
"model",
|
| 365 |
+
"latency_ms",
|
| 366 |
+
"cost_usd",
|
| 367 |
"entities",
|
| 368 |
]
|
| 369 |
)
|
|
|
|
| 371 |
entities_cell = "; ".join(
|
| 372 |
f"{ent.get('type', '')}:{ent.get('text', '')}" for ent in _row_entities(r)
|
| 373 |
)
|
| 374 |
+
writer.writerow(
|
| 375 |
+
[r[0], r[1], r[2], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], entities_cell]
|
| 376 |
+
)
|
| 377 |
|
| 378 |
# utf-8-sig (BOM) so Excel opens the file with correct encoding.
|
| 379 |
return buffer.getvalue().encode("utf-8-sig")
|
| 380 |
|
| 381 |
|
| 382 |
+
def export_records(
|
| 383 |
+
fmt: str,
|
| 384 |
+
limit: int | None = None,
|
| 385 |
+
engine: str | None = None,
|
| 386 |
+
topic: str | None = None,
|
| 387 |
+
sentiment: str | None = None,
|
| 388 |
+
) -> tuple[bytes, str]:
|
| 389 |
"""
|
| 390 |
Export stored (anonymized) records in the given format.
|
| 391 |
|
| 392 |
Returns ``(content_bytes, media_type)``. Raises ``ValueError`` for an
|
| 393 |
unsupported ``fmt`` so the API layer can turn it into a clean 400
|
| 394 |
+
response. ``limit`` caps the number of most recent records exported
|
| 395 |
+
(``None`` exports everything); ``engine``/``topic``/``sentiment``
|
| 396 |
+
optionally filter, same as ``get_records``.
|
| 397 |
"""
|
| 398 |
fmt = (fmt or "xml").strip().lower()
|
| 399 |
if fmt not in EXPORT_FORMATS:
|
| 400 |
supported = ", ".join(sorted(EXPORT_FORMATS))
|
| 401 |
raise ValueError(f"Unsupported export format '{fmt}'. Supported: {supported}.")
|
| 402 |
|
| 403 |
+
rows = _fetch_export_rows(limit, engine, topic, sentiment)
|
| 404 |
exporter = {"xml": _export_xml, "json": _export_json, "csv": _export_csv}[fmt]
|
| 405 |
return exporter(rows), EXPORT_FORMATS[fmt]
|
docs/class_diagram.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
# Class diagram -
|
| 2 |
|
| 3 |
Modules are shown as facade classes over their public functions. GitHub
|
| 4 |
renders this Mermaid diagram directly. Compared to V3, `Database.export_xml()`
|
|
@@ -14,6 +14,27 @@ process_batch` calls those directly instead of looping over
|
|
| 14 |
`API.ingest_file` start a background thread instead of processing
|
| 15 |
synchronously - see "Background ingest jobs (progress bar + timer)".
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
```mermaid
|
| 18 |
classDiagram
|
| 19 |
class API {
|
|
@@ -21,12 +42,13 @@ classDiagram
|
|
| 21 |
+home() FileResponse
|
| 22 |
+health() dict
|
| 23 |
+list_models() dict
|
|
|
|
| 24 |
+analyze(payload) dict
|
| 25 |
+predict(payload) dict
|
| 26 |
-
+ingest_file(file, sentiment_model, ner_model, topic_model) dict
|
| 27 |
+ingest_status(job_id) dict
|
| 28 |
-
+records(limit) list
|
| 29 |
-
+export_records(format, limit) Response
|
| 30 |
+get_stats() dict
|
| 31 |
}
|
| 32 |
|
|
@@ -97,13 +119,41 @@ classDiagram
|
|
| 97 |
<<db.py>>
|
| 98 |
-export_formats: dict = {xml, json, csv}
|
| 99 |
+save_record(result, source) void
|
| 100 |
-
+get_records(limit) list
|
| 101 |
+stats() dict
|
| 102 |
-
+export_records(fmt, limit) bytes
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
}
|
| 104 |
|
| 105 |
API --> IngestService : parses uploaded files
|
| 106 |
-
API --> Pipeline : runs analysis (in a background thread)
|
|
|
|
| 107 |
API --> JobTracker : creates/polls ingest jobs
|
| 108 |
API --> Database : reads/writes/export records
|
| 109 |
API --> ModelRegistry : lists cached models
|
|
@@ -115,4 +165,11 @@ classDiagram
|
|
| 115 |
NERProcessor --> ModelRegistry : loads non-default HF models
|
| 116 |
TopicClassifier --> ModelRegistry : loads non-default HF models
|
| 117 |
SentimentAnalyzer --> ModelRegistry : loads non-default HF models
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
```
|
|
|
|
| 1 |
+
# Class diagram - V8
|
| 2 |
|
| 3 |
Modules are shown as facade classes over their public functions. GitHub
|
| 4 |
renders this Mermaid diagram directly. Compared to V3, `Database.export_xml()`
|
|
|
|
| 14 |
`API.ingest_file` start a background thread instead of processing
|
| 15 |
synchronously - see "Background ingest jobs (progress bar + timer)".
|
| 16 |
|
| 17 |
+
V8 adds a second, independent branch alongside `Pipeline`: the `llm_client`
|
| 18 |
+
package, which resolves the same three tasks (sentiment, NER, topic) with a
|
| 19 |
+
single call to an LLM provider instead of three local models. `API` gains
|
| 20 |
+
`list_engines()` and branches `analyze()`/`ingest_file()` on an `engine`
|
| 21 |
+
field between `Pipeline` (local, unchanged) and `LLMPipeline` (new). Both
|
| 22 |
+
branches always go through `Anonymizer` first - `LLMPipeline` wraps the
|
| 23 |
+
same module via `_load_presidio_anonymizer()` - so pseudonymization happens
|
| 24 |
+
locally before any text reaches a provider API. `LLMPipeline` delegates the
|
| 25 |
+
actual model call to one of three `LLMClient` subclasses (`AnthropicClient`,
|
| 26 |
+
`OpenAIClient`, `GeminiClient`) chosen by `get_client(provider)`, each
|
| 27 |
+
returning the same `AnalysisResult` contract regardless of provider. `API`
|
| 28 |
+
maps that result onto the same shape `Pipeline.process_message` returns and
|
| 29 |
+
persists it via the same `Database.save_record` used by the local engine,
|
| 30 |
+
tagged with `engine`/`provider`/`model`/`latency_ms`/`cost_usd` - both
|
| 31 |
+
engines' results therefore live in the same `records` table and are listed/
|
| 32 |
+
exported together, see the README section "Optional LLM engine (Claude /
|
| 33 |
+
Gemini / OpenAI)". A dedicated BERT-vs-LLM comparison layer (its own
|
| 34 |
+
database, agreement metrics, dashboard) was considered but dropped from
|
| 35 |
+
this version; that comparison is instead run manually and written up in
|
| 36 |
+
the thesis.
|
| 37 |
+
|
| 38 |
```mermaid
|
| 39 |
classDiagram
|
| 40 |
class API {
|
|
|
|
| 42 |
+home() FileResponse
|
| 43 |
+health() dict
|
| 44 |
+list_models() dict
|
| 45 |
+
+list_engines() dict
|
| 46 |
+analyze(payload) dict
|
| 47 |
+predict(payload) dict
|
| 48 |
+
+ingest_file(file, engine, llm_mode, sentiment_model, ner_model, topic_model) dict
|
| 49 |
+ingest_status(job_id) dict
|
| 50 |
+
+records(limit, engine, topic, sentiment) list
|
| 51 |
+
+export_records(format, limit, engine, topic, sentiment) Response
|
| 52 |
+get_stats() dict
|
| 53 |
}
|
| 54 |
|
|
|
|
| 119 |
<<db.py>>
|
| 120 |
-export_formats: dict = {xml, json, csv}
|
| 121 |
+save_record(result, source) void
|
| 122 |
+
+get_records(limit, engine, topic, sentiment) list
|
| 123 |
+stats() dict
|
| 124 |
+
+export_records(fmt, limit, engine, topic, sentiment) bytes
|
| 125 |
+
}
|
| 126 |
+
note for Database "records columns since V8:\nengine, provider, model,\nlatency_ms, cost_usd\n(NULL for the local engine)\nget_records/export_records share a\n_build_filter() helper: optional\nengine ('local'|'llm'), topic and\nsentiment filters, combinable"
|
| 127 |
+
|
| 128 |
+
class LLMPipeline {
|
| 129 |
+
<<llm_client/pipeline.py>>
|
| 130 |
+
-provider: str
|
| 131 |
+
-mode: "pre_pseudonymized" | "raw"
|
| 132 |
+
+analyze(text) AnalysisResult
|
| 133 |
+
+analyze_batch(texts, on_progress) list~AnalysisResult~
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
class LLMClient {
|
| 137 |
+
<<llm_client/client.py>>
|
| 138 |
+
<<abstract>>
|
| 139 |
+
+analyze(text) tuple~dict, CallMeta~
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
class AnthropicClient {
|
| 143 |
+
<<llm_client/client.py>>
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
class OpenAIClient {
|
| 147 |
+
<<llm_client/client.py>>
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
class GeminiClient {
|
| 151 |
+
<<llm_client/client.py>>
|
| 152 |
}
|
| 153 |
|
| 154 |
API --> IngestService : parses uploaded files
|
| 155 |
+
API --> Pipeline : runs local analysis (in a background thread)
|
| 156 |
+
API --> LLMPipeline : runs LLM analysis (engine != local)
|
| 157 |
API --> JobTracker : creates/polls ingest jobs
|
| 158 |
API --> Database : reads/writes/export records
|
| 159 |
API --> ModelRegistry : lists cached models
|
|
|
|
| 165 |
NERProcessor --> ModelRegistry : loads non-default HF models
|
| 166 |
TopicClassifier --> ModelRegistry : loads non-default HF models
|
| 167 |
SentimentAnalyzer --> ModelRegistry : loads non-default HF models
|
| 168 |
+
LLMPipeline --> Anonymizer : pseudonymizes before any provider call
|
| 169 |
+
LLMPipeline --> LLMClient : delegates the analysis call
|
| 170 |
+
LLMClient <|-- AnthropicClient
|
| 171 |
+
LLMClient <|-- OpenAIClient
|
| 172 |
+
LLMClient <|-- GeminiClient
|
| 173 |
+
LLMPipeline --> JobTracker : reports progress via on_progress (ingest)
|
| 174 |
+
API --> Database : maps LLMPipeline result onto save_record too
|
| 175 |
```
|
llm_client/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
llm_client – druhá větev systému pro analýzu konverzací.
|
| 3 |
+
|
| 4 |
+
Zatímco původní větev provádí NER, klasifikaci témat, analýzu sentimentu
|
| 5 |
+
a pseudonymizaci lokálními modely typu BERT, tato větev řeší tytéž úlohy
|
| 6 |
+
jediným voláním generativního modelu přes API - vždy až nad textem, který
|
| 7 |
+
už prošel stejnou lokální pseudonymizací jako BERT větev. Výsledky obou
|
| 8 |
+
větví se ukládají do stejné databáze (`db.py` hlavní aplikace) a zobrazují
|
| 9 |
+
ve stejném seznamu záznamů.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from .config import SETTINGS, PROVIDERS
|
| 13 |
+
from .pipeline import LLMPipeline
|
| 14 |
+
from .schemas import AnalysisResult
|
| 15 |
+
|
| 16 |
+
__version__ = "1.0.0"
|
| 17 |
+
|
| 18 |
+
__all__ = [
|
| 19 |
+
"SETTINGS",
|
| 20 |
+
"PROVIDERS",
|
| 21 |
+
"LLMPipeline",
|
| 22 |
+
"AnalysisResult",
|
| 23 |
+
]
|
llm_client/client.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Klienti jednotlivých poskytovatelů LLM.
|
| 3 |
+
|
| 4 |
+
Abstrakce `LLMClient` skrývá rozdíly mezi Anthropic Messages API a OpenAI
|
| 5 |
+
Chat Completions API. Volající kód pracuje pouze s metodou `analyze()`,
|
| 6 |
+
která vrací dvojici (data, metadata) – data odpovídají schématu z modulu
|
| 7 |
+
`prompts`, metadata obsahují latenci, tokeny a náklad.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
import time
|
| 14 |
+
from dataclasses import dataclass
|
| 15 |
+
from typing import Any, Dict, Tuple
|
| 16 |
+
|
| 17 |
+
from . import prompts
|
| 18 |
+
from .config import PROVIDERS, SETTINGS, ProviderConfig
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class LLMError(RuntimeError):
|
| 22 |
+
pass
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@dataclass
|
| 26 |
+
class CallMeta:
|
| 27 |
+
latency_ms: int
|
| 28 |
+
tokens_in: int
|
| 29 |
+
tokens_out: int
|
| 30 |
+
cost_usd: float
|
| 31 |
+
model: str
|
| 32 |
+
provider: str
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class LLMClient:
|
| 36 |
+
"""Základní rozhraní."""
|
| 37 |
+
|
| 38 |
+
def __init__(self, cfg: ProviderConfig):
|
| 39 |
+
self.cfg = cfg
|
| 40 |
+
if not cfg.available:
|
| 41 |
+
raise LLMError(
|
| 42 |
+
f"Chybí API klíč. Nastav proměnnou prostředí {cfg.api_key_env}."
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
def analyze(self, text: str) -> Tuple[Dict[str, Any], CallMeta]:
|
| 46 |
+
raise NotImplementedError
|
| 47 |
+
|
| 48 |
+
def _cost(self, tokens_in: int, tokens_out: int) -> float:
|
| 49 |
+
return (
|
| 50 |
+
tokens_in / 1_000_000 * self.cfg.price_in_per_mtok
|
| 51 |
+
+ tokens_out / 1_000_000 * self.cfg.price_out_per_mtok
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class AnthropicClient(LLMClient):
|
| 56 |
+
def __init__(self, cfg: ProviderConfig):
|
| 57 |
+
super().__init__(cfg)
|
| 58 |
+
try:
|
| 59 |
+
import anthropic
|
| 60 |
+
except ImportError as exc: # pragma: no cover
|
| 61 |
+
raise LLMError("Nainstaluj balíček 'anthropic' (pip install anthropic).") from exc
|
| 62 |
+
self._sdk = anthropic.Anthropic(
|
| 63 |
+
api_key=cfg.api_key, timeout=SETTINGS.request_timeout_s
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
def analyze(self, text: str) -> Tuple[Dict[str, Any], CallMeta]:
|
| 67 |
+
started = time.perf_counter()
|
| 68 |
+
response = self._sdk.messages.create(
|
| 69 |
+
model=self.cfg.model,
|
| 70 |
+
max_tokens=self.cfg.max_tokens,
|
| 71 |
+
temperature=self.cfg.temperature,
|
| 72 |
+
system=prompts.SYSTEM_PROMPT,
|
| 73 |
+
tools=[prompts.anthropic_tool()],
|
| 74 |
+
tool_choice={"type": "tool", "name": prompts.TOOL_NAME},
|
| 75 |
+
messages=prompts.build_messages(text),
|
| 76 |
+
)
|
| 77 |
+
latency = int((time.perf_counter() - started) * 1000)
|
| 78 |
+
|
| 79 |
+
payload: Dict[str, Any] | None = None
|
| 80 |
+
for block in response.content:
|
| 81 |
+
if getattr(block, "type", None) == "tool_use":
|
| 82 |
+
payload = block.input
|
| 83 |
+
break
|
| 84 |
+
if payload is None:
|
| 85 |
+
raise LLMError("Model nevrátil strukturovaný výstup (chybí blok tool_use).")
|
| 86 |
+
|
| 87 |
+
tokens_in = response.usage.input_tokens
|
| 88 |
+
tokens_out = response.usage.output_tokens
|
| 89 |
+
meta = CallMeta(
|
| 90 |
+
latency_ms=latency,
|
| 91 |
+
tokens_in=tokens_in,
|
| 92 |
+
tokens_out=tokens_out,
|
| 93 |
+
cost_usd=self._cost(tokens_in, tokens_out),
|
| 94 |
+
model=self.cfg.model,
|
| 95 |
+
provider="anthropic",
|
| 96 |
+
)
|
| 97 |
+
return payload, meta
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class OpenAIClient(LLMClient):
|
| 101 |
+
def __init__(self, cfg: ProviderConfig):
|
| 102 |
+
super().__init__(cfg)
|
| 103 |
+
try:
|
| 104 |
+
from openai import OpenAI
|
| 105 |
+
except ImportError as exc: # pragma: no cover
|
| 106 |
+
raise LLMError("Nainstaluj balíček 'openai' (pip install openai).") from exc
|
| 107 |
+
self._sdk = OpenAI(api_key=cfg.api_key, timeout=SETTINGS.request_timeout_s)
|
| 108 |
+
|
| 109 |
+
def analyze(self, text: str) -> Tuple[Dict[str, Any], CallMeta]:
|
| 110 |
+
started = time.perf_counter()
|
| 111 |
+
response = self._sdk.chat.completions.create(
|
| 112 |
+
model=self.cfg.model,
|
| 113 |
+
max_tokens=self.cfg.max_tokens,
|
| 114 |
+
temperature=self.cfg.temperature,
|
| 115 |
+
response_format=prompts.openai_response_format(),
|
| 116 |
+
messages=[{"role": "system", "content": prompts.SYSTEM_PROMPT}]
|
| 117 |
+
+ prompts.build_messages(text),
|
| 118 |
+
)
|
| 119 |
+
latency = int((time.perf_counter() - started) * 1000)
|
| 120 |
+
|
| 121 |
+
content = response.choices[0].message.content
|
| 122 |
+
if not content:
|
| 123 |
+
raise LLMError("Model vrátil prázdnou odpověď.")
|
| 124 |
+
payload = json.loads(content)
|
| 125 |
+
|
| 126 |
+
usage = response.usage
|
| 127 |
+
meta = CallMeta(
|
| 128 |
+
latency_ms=latency,
|
| 129 |
+
tokens_in=usage.prompt_tokens,
|
| 130 |
+
tokens_out=usage.completion_tokens,
|
| 131 |
+
cost_usd=self._cost(usage.prompt_tokens, usage.completion_tokens),
|
| 132 |
+
model=self.cfg.model,
|
| 133 |
+
provider="openai",
|
| 134 |
+
)
|
| 135 |
+
return payload, meta
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class GeminiClient(LLMClient):
|
| 139 |
+
"""
|
| 140 |
+
Google Gemini (`google-generativeai`). Strukturovaný výstup je vynucen
|
| 141 |
+
přes `response_mime_type="application/json"` + `response_schema` -
|
| 142 |
+
schéma vychází ze stejného `prompts.build_input_schema()` jako u
|
| 143 |
+
Anthropic/OpenAI, ale přes `prompts.gemini_schema()`, který navíc
|
| 144 |
+
odstraní klíče `minimum`/`maximum` - Gemini je ve svém `Schema` proto
|
| 145 |
+
nezná a s nimi by volání rovnou odmítlo.
|
| 146 |
+
"""
|
| 147 |
+
|
| 148 |
+
def __init__(self, cfg: ProviderConfig):
|
| 149 |
+
super().__init__(cfg)
|
| 150 |
+
try:
|
| 151 |
+
import google.generativeai as genai
|
| 152 |
+
except ImportError as exc: # pragma: no cover
|
| 153 |
+
raise LLMError(
|
| 154 |
+
"Nainstaluj balíček 'google-generativeai' (pip install google-generativeai)."
|
| 155 |
+
) from exc
|
| 156 |
+
genai.configure(api_key=cfg.api_key)
|
| 157 |
+
self._genai = genai
|
| 158 |
+
self._model = genai.GenerativeModel(
|
| 159 |
+
cfg.model, system_instruction=prompts.SYSTEM_PROMPT
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
def analyze(self, text: str) -> Tuple[Dict[str, Any], CallMeta]:
|
| 163 |
+
started = time.perf_counter()
|
| 164 |
+
response = self._model.generate_content(
|
| 165 |
+
prompts.USER_TEMPLATE.format(text=text),
|
| 166 |
+
generation_config=self._genai.GenerationConfig(
|
| 167 |
+
temperature=self.cfg.temperature,
|
| 168 |
+
max_output_tokens=self.cfg.max_tokens,
|
| 169 |
+
response_mime_type="application/json",
|
| 170 |
+
response_schema=prompts.gemini_schema(),
|
| 171 |
+
),
|
| 172 |
+
)
|
| 173 |
+
latency = int((time.perf_counter() - started) * 1000)
|
| 174 |
+
|
| 175 |
+
content = response.text
|
| 176 |
+
if not content:
|
| 177 |
+
raise LLMError("Model nevrátil žádný obsah.")
|
| 178 |
+
payload = json.loads(content)
|
| 179 |
+
|
| 180 |
+
usage = getattr(response, "usage_metadata", None)
|
| 181 |
+
tokens_in = getattr(usage, "prompt_token_count", 0) or 0
|
| 182 |
+
tokens_out = getattr(usage, "candidates_token_count", 0) or 0
|
| 183 |
+
meta = CallMeta(
|
| 184 |
+
latency_ms=latency,
|
| 185 |
+
tokens_in=tokens_in,
|
| 186 |
+
tokens_out=tokens_out,
|
| 187 |
+
cost_usd=self._cost(tokens_in, tokens_out),
|
| 188 |
+
model=self.cfg.model,
|
| 189 |
+
provider="google",
|
| 190 |
+
)
|
| 191 |
+
return payload, meta
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
_REGISTRY = {"anthropic": AnthropicClient, "openai": OpenAIClient, "google": GeminiClient}
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def get_client(provider: str | None = None) -> LLMClient:
|
| 198 |
+
provider = provider or SETTINGS.default_provider
|
| 199 |
+
if provider not in _REGISTRY:
|
| 200 |
+
raise LLMError(
|
| 201 |
+
f"Neznámý poskytovatel '{provider}'. Dostupné: {', '.join(_REGISTRY)}."
|
| 202 |
+
)
|
| 203 |
+
return _REGISTRY[provider](PROVIDERS[provider])
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def call_with_retry(client: LLMClient, text: str) -> Tuple[Dict[str, Any], CallMeta]:
|
| 207 |
+
"""Volání s exponenciálním odstupem – ošetřuje rate limit a výpadky sítě."""
|
| 208 |
+
last: Exception | None = None
|
| 209 |
+
for attempt in range(SETTINGS.max_retries):
|
| 210 |
+
try:
|
| 211 |
+
return client.analyze(text)
|
| 212 |
+
except Exception as exc: # noqa: BLE001 – záměrně široké, chyba se loguje
|
| 213 |
+
last = exc
|
| 214 |
+
if attempt == SETTINGS.max_retries - 1:
|
| 215 |
+
break
|
| 216 |
+
time.sleep(2**attempt)
|
| 217 |
+
raise LLMError(f"Volání selhalo po {SETTINGS.max_retries} pokusech: {last}")
|
llm_client/config.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Konfigurace LLM větve systému.
|
| 3 |
+
|
| 4 |
+
Veškeré citlivé hodnoty (API klíče) se načítají výhradně z proměnných
|
| 5 |
+
prostředí – nikdy nejsou uloženy v repozitáři ani v databázi.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import os
|
| 11 |
+
from dataclasses import dataclass, field
|
| 12 |
+
from typing import Dict, List
|
| 13 |
+
|
| 14 |
+
# --------------------------------------------------------------------------
|
| 15 |
+
# Sjednocené taxonomie
|
| 16 |
+
#
|
| 17 |
+
# Aby bylo srovnání BERT vs. LLM metodicky korektní, musí oba enginy
|
| 18 |
+
# produkovat výstupy nad *identickou* množinou tříd. Taxonomie je proto
|
| 19 |
+
# definována centrálně a do promptu LLM se vkládá dynamicky.
|
| 20 |
+
# --------------------------------------------------------------------------
|
| 21 |
+
|
| 22 |
+
SENTIMENT_LABELS: List[str] = ["negative", "neutral", "positive"]
|
| 23 |
+
|
| 24 |
+
# Odpovídá výstupu modelu dslim/bert-base-NER (CoNLL-2003)
|
| 25 |
+
ENTITY_LABELS: List[str] = ["PER", "ORG", "LOC", "MISC"]
|
| 26 |
+
|
| 27 |
+
# Převzato přímo z processors.topics.DEFAULT_LABELS (zero-shot klasifikátor
|
| 28 |
+
# BERT větve), aby LLM klasifikoval do přesně stejné množiny témat - jinak
|
| 29 |
+
# by srovnání měřilo rozdíl v číselnících, ne rozdíl v modelech.
|
| 30 |
+
try:
|
| 31 |
+
from processors.topics import DEFAULT_LABELS as TOPIC_LABELS # type: ignore
|
| 32 |
+
except Exception: # pragma: no cover - fallback when imported outside the app
|
| 33 |
+
TOPIC_LABELS: List[str] = [
|
| 34 |
+
"billing and payments",
|
| 35 |
+
"technical issue",
|
| 36 |
+
"complaint",
|
| 37 |
+
"product question",
|
| 38 |
+
"account management",
|
| 39 |
+
"cancellation",
|
| 40 |
+
"delivery and shipping",
|
| 41 |
+
"praise and positive feedback",
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
# Typy PII sjednocené s Microsoft Presidio
|
| 45 |
+
PII_LABELS: List[str] = [
|
| 46 |
+
"PERSON",
|
| 47 |
+
"EMAIL_ADDRESS",
|
| 48 |
+
"PHONE_NUMBER",
|
| 49 |
+
"LOCATION",
|
| 50 |
+
"CREDIT_CARD",
|
| 51 |
+
"IBAN_CODE",
|
| 52 |
+
"DATE_TIME",
|
| 53 |
+
"ORGANIZATION",
|
| 54 |
+
"ID_NUMBER",
|
| 55 |
+
]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@dataclass
|
| 59 |
+
class ProviderConfig:
|
| 60 |
+
"""Popis jednoho poskytovatele LLM."""
|
| 61 |
+
|
| 62 |
+
name: str
|
| 63 |
+
model: str
|
| 64 |
+
api_key_env: str
|
| 65 |
+
# cena v USD za 1 milion tokenů (vstup, výstup)
|
| 66 |
+
price_in_per_mtok: float
|
| 67 |
+
price_out_per_mtok: float
|
| 68 |
+
max_tokens: int = 2048
|
| 69 |
+
temperature: float = 0.0
|
| 70 |
+
|
| 71 |
+
@property
|
| 72 |
+
def api_key(self) -> str | None:
|
| 73 |
+
return os.getenv(self.api_key_env)
|
| 74 |
+
|
| 75 |
+
@property
|
| 76 |
+
def available(self) -> bool:
|
| 77 |
+
return bool(self.api_key)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# Ceny je nutné před finálním měřením ověřit v aktuálním ceníku poskytovatele;
|
| 81 |
+
# jsou zde uvedeny jako výchozí hodnoty pro výpočet nákladovosti.
|
| 82 |
+
PROVIDERS: Dict[str, ProviderConfig] = {
|
| 83 |
+
"anthropic": ProviderConfig(
|
| 84 |
+
name="anthropic",
|
| 85 |
+
model=os.getenv("ANTHROPIC_MODEL", "claude-sonnet-5"),
|
| 86 |
+
api_key_env="ANTHROPIC_API_KEY",
|
| 87 |
+
price_in_per_mtok=float(os.getenv("ANTHROPIC_PRICE_IN", "3.00")),
|
| 88 |
+
price_out_per_mtok=float(os.getenv("ANTHROPIC_PRICE_OUT", "15.00")),
|
| 89 |
+
),
|
| 90 |
+
"openai": ProviderConfig(
|
| 91 |
+
name="openai",
|
| 92 |
+
model=os.getenv("OPENAI_MODEL", "gpt-4o-mini"),
|
| 93 |
+
api_key_env="OPENAI_API_KEY",
|
| 94 |
+
price_in_per_mtok=float(os.getenv("OPENAI_PRICE_IN", "0.15")),
|
| 95 |
+
price_out_per_mtok=float(os.getenv("OPENAI_PRICE_OUT", "0.60")),
|
| 96 |
+
),
|
| 97 |
+
"google": ProviderConfig(
|
| 98 |
+
name="google",
|
| 99 |
+
model=os.getenv("GEMINI_MODEL", "gemini-2.5-flash"),
|
| 100 |
+
api_key_env="GEMINI_API_KEY",
|
| 101 |
+
price_in_per_mtok=float(os.getenv("GEMINI_PRICE_IN", "0.30")),
|
| 102 |
+
price_out_per_mtok=float(os.getenv("GEMINI_PRICE_OUT", "2.50")),
|
| 103 |
+
),
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
@dataclass
|
| 108 |
+
class Settings:
|
| 109 |
+
default_provider: str = field(
|
| 110 |
+
default_factory=lambda: os.getenv("LLM_PROVIDER", "google")
|
| 111 |
+
)
|
| 112 |
+
# 'pre_pseudonymized' = text je před odesláním do API zbaven PII lokálně
|
| 113 |
+
# 'raw' = do API jde originální text (pouze pro srovnávací experiment)
|
| 114 |
+
default_mode: str = field(default_factory=lambda: os.getenv("LLM_MODE", "pre_pseudonymized"))
|
| 115 |
+
max_retries: int = 3
|
| 116 |
+
request_timeout_s: int = 60
|
| 117 |
+
# maximální počet souběžných požadavků při dávkovém zpracování
|
| 118 |
+
concurrency: int = int(os.getenv("LLM_CONCURRENCY", "4"))
|
| 119 |
+
# tvrdá pojistka: bez explicitního souhlasu nelze poslat surový text ven
|
| 120 |
+
allow_raw_mode: bool = os.getenv("LLM_ALLOW_RAW", "false").lower() == "true"
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
SETTINGS = Settings()
|
llm_client/pipeline.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
LLM pipeline – protějšek BERT pipeline.
|
| 3 |
+
|
| 4 |
+
Obě třídy sdílejí metodu `analyze(text) -> AnalysisResult`, takže je lze
|
| 5 |
+
v systému zaměnit bez zásahu do volajícího kódu.
|
| 6 |
+
|
| 7 |
+
Režimy zpracování (parametr `mode`):
|
| 8 |
+
|
| 9 |
+
* ``pre_pseudonymized`` – výchozí. Text je nejprve lokálně zbaven osobních
|
| 10 |
+
údajů (Presidio) a teprve poté odeslán do API poskytovatele. Ven z
|
| 11 |
+
infrastruktury tak neopouštějí osobní údaje a odpadá nutnost řešit
|
| 12 |
+
poskytovatele jako zpracovatele osobních údajů podle čl. 28 GDPR.
|
| 13 |
+
* ``raw`` – originální text jde přímo do API a pseudonymizaci provádí model.
|
| 14 |
+
Slouží výhradně k experimentálnímu porovnání úspěšnosti detekce PII.
|
| 15 |
+
Vyžaduje explicitní povolení proměnnou ``LLM_ALLOW_RAW=true``.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import concurrent.futures
|
| 21 |
+
import logging
|
| 22 |
+
import re
|
| 23 |
+
from types import SimpleNamespace
|
| 24 |
+
from typing import Any, Callable, Iterable, List, Optional
|
| 25 |
+
|
| 26 |
+
from .client import LLMClient, call_with_retry, get_client
|
| 27 |
+
from .config import SETTINGS
|
| 28 |
+
from .schemas import AnalysisResult, Entity, PIISpan, Sentiment, TopicScore
|
| 29 |
+
|
| 30 |
+
log = logging.getLogger(__name__)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# --------------------------------------------------------------------------
|
| 34 |
+
# Lokální pseudonymizace před odesláním
|
| 35 |
+
# --------------------------------------------------------------------------
|
| 36 |
+
|
| 37 |
+
def _load_presidio_anonymizer() -> Optional[Callable[[str], tuple[str, list]]]:
|
| 38 |
+
"""
|
| 39 |
+
Zkusí připojit pseudonymizér z BERT větve systému (`processors.anonymizer`).
|
| 40 |
+
Ten nemá jedinou funkci `pseudonymize()` s obojím výstupem - má
|
| 41 |
+
`anonymize_text(text) -> str` a `detect_pii(text) -> list[dict]` zvlášť
|
| 42 |
+
({"type","start","end","score","text"}). Zde je spojíme do stejného
|
| 43 |
+
tvaru `(masked_text, spans)`, jaký LLM pipeline očekává, aby šlo použít
|
| 44 |
+
přesně tu anonymizaci (Presidio + regex fallback), kterou používá i
|
| 45 |
+
hlavní BERT větev - žádná druhá, oddělená implementace stejné věci.
|
| 46 |
+
Pokud modul není dostupný, vrátí None a použije se záložní regex níže.
|
| 47 |
+
"""
|
| 48 |
+
try:
|
| 49 |
+
from processors.anonymizer import anonymize_text, detect_pii # type: ignore
|
| 50 |
+
except Exception: # noqa: BLE001
|
| 51 |
+
log.warning("processors.anonymizer není dostupný, používá se záložní regex.")
|
| 52 |
+
return None
|
| 53 |
+
|
| 54 |
+
def pseudonymize(text: str) -> tuple[str, list]:
|
| 55 |
+
masked = anonymize_text(text)
|
| 56 |
+
spans = [
|
| 57 |
+
SimpleNamespace(
|
| 58 |
+
text=item.get("text", ""),
|
| 59 |
+
entity_type=item.get("type", "ID_NUMBER"),
|
| 60 |
+
start=item.get("start"),
|
| 61 |
+
end=item.get("end"),
|
| 62 |
+
placeholder=None,
|
| 63 |
+
)
|
| 64 |
+
for item in detect_pii(text)
|
| 65 |
+
]
|
| 66 |
+
return masked, spans
|
| 67 |
+
|
| 68 |
+
return pseudonymize
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
_FALLBACK_PATTERNS = [
|
| 72 |
+
("EMAIL_ADDRESS", re.compile(r"\b[\w.%+-]+@[\w.-]+\.[A-Za-z]{2,}\b")),
|
| 73 |
+
("PHONE_NUMBER", re.compile(r"(?<!\d)(?:\+\d{1,3}[ -]?)?(?:\d[ -]?){9,12}(?!\d)")),
|
| 74 |
+
("CREDIT_CARD", re.compile(r"\b(?:\d[ -]?){13,16}\b")),
|
| 75 |
+
("IBAN_CODE", re.compile(r"\b[A-Z]{2}\d{2}[A-Z0-9]{11,30}\b")),
|
| 76 |
+
]
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _fallback_pseudonymize(text: str) -> tuple[str, List[PIISpan]]:
|
| 80 |
+
spans: List[PIISpan] = []
|
| 81 |
+
counters: dict[str, int] = {}
|
| 82 |
+
out = text
|
| 83 |
+
for label, pattern in _FALLBACK_PATTERNS:
|
| 84 |
+
for match in list(pattern.finditer(out)):
|
| 85 |
+
counters[label] = counters.get(label, 0) + 1
|
| 86 |
+
placeholder = f"<{label}_{counters[label]}>"
|
| 87 |
+
spans.append(
|
| 88 |
+
PIISpan(text=match.group(), label=label, placeholder=placeholder)
|
| 89 |
+
)
|
| 90 |
+
out = out.replace(match.group(), placeholder, 1)
|
| 91 |
+
return out, spans
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class LLMPipeline:
|
| 95 |
+
"""Analýza zprávy pomocí generativního modelu přes API."""
|
| 96 |
+
|
| 97 |
+
engine = "llm"
|
| 98 |
+
|
| 99 |
+
def __init__(
|
| 100 |
+
self,
|
| 101 |
+
provider: str | None = None,
|
| 102 |
+
mode: str | None = None,
|
| 103 |
+
client: LLMClient | None = None,
|
| 104 |
+
):
|
| 105 |
+
self.provider = provider or SETTINGS.default_provider
|
| 106 |
+
self.mode = mode or SETTINGS.default_mode
|
| 107 |
+
if self.mode == "raw" and not SETTINGS.allow_raw_mode:
|
| 108 |
+
raise ValueError(
|
| 109 |
+
"Režim 'raw' odesílá nemaskovaný text mimo systém. "
|
| 110 |
+
"Povol jej vědomě proměnnou LLM_ALLOW_RAW=true."
|
| 111 |
+
)
|
| 112 |
+
self._client = client or get_client(self.provider)
|
| 113 |
+
self._presidio = _load_presidio_anonymizer()
|
| 114 |
+
|
| 115 |
+
# ------------------------------------------------------------------
|
| 116 |
+
def _prepare(self, text: str) -> tuple[str, List[PIISpan]]:
|
| 117 |
+
if self.mode != "pre_pseudonymized":
|
| 118 |
+
return text, []
|
| 119 |
+
if self._presidio is not None:
|
| 120 |
+
masked, raw_spans = self._presidio(text)
|
| 121 |
+
spans = [
|
| 122 |
+
PIISpan(
|
| 123 |
+
text=getattr(s, "text", ""),
|
| 124 |
+
label=getattr(s, "entity_type", "ID_NUMBER"),
|
| 125 |
+
start=getattr(s, "start", None),
|
| 126 |
+
end=getattr(s, "end", None),
|
| 127 |
+
placeholder=getattr(s, "placeholder", None),
|
| 128 |
+
)
|
| 129 |
+
for s in raw_spans
|
| 130 |
+
]
|
| 131 |
+
return masked, spans
|
| 132 |
+
return _fallback_pseudonymize(text)
|
| 133 |
+
|
| 134 |
+
# ------------------------------------------------------------------
|
| 135 |
+
def analyze(self, text: str) -> AnalysisResult:
|
| 136 |
+
sent_text, local_spans = self._prepare(text)
|
| 137 |
+
|
| 138 |
+
result = AnalysisResult(
|
| 139 |
+
engine=self.engine,
|
| 140 |
+
provider=self.provider,
|
| 141 |
+
mode=self.mode,
|
| 142 |
+
)
|
| 143 |
+
try:
|
| 144 |
+
payload, meta = call_with_retry(self._client, sent_text)
|
| 145 |
+
except Exception as exc: # noqa: BLE001
|
| 146 |
+
result.error = str(exc)
|
| 147 |
+
log.error("Analýza selhala: %s", exc)
|
| 148 |
+
return result
|
| 149 |
+
|
| 150 |
+
result.model = meta.model
|
| 151 |
+
result.provider = meta.provider
|
| 152 |
+
result.latency_ms = meta.latency_ms
|
| 153 |
+
result.tokens_in = meta.tokens_in
|
| 154 |
+
result.tokens_out = meta.tokens_out
|
| 155 |
+
result.cost_usd = meta.cost_usd
|
| 156 |
+
result.raw_response = payload
|
| 157 |
+
|
| 158 |
+
result.sentiment = Sentiment(**payload.get("sentiment", {}))
|
| 159 |
+
result.entities = [Entity(**e) for e in payload.get("entities", [])]
|
| 160 |
+
result.topics = [TopicScore(**t) for t in payload.get("topics", [])]
|
| 161 |
+
|
| 162 |
+
model_spans = [PIISpan(**p) for p in payload.get("pii", [])]
|
| 163 |
+
# V režimu pre_pseudonymized je autoritativní lokální detekce;
|
| 164 |
+
# nálezy modelu se přidávají jako doplněk (reziduální PII).
|
| 165 |
+
result.pii = local_spans + model_spans if local_spans else model_spans
|
| 166 |
+
result.pseudonymized_text = payload.get("pseudonymized_text") or sent_text
|
| 167 |
+
|
| 168 |
+
# Doplnění offsetů, které model nevrací spolehlivě.
|
| 169 |
+
_fill_offsets(result.entities, sent_text)
|
| 170 |
+
return result
|
| 171 |
+
|
| 172 |
+
# ------------------------------------------------------------------
|
| 173 |
+
def analyze_batch(
|
| 174 |
+
self,
|
| 175 |
+
texts: Iterable[str],
|
| 176 |
+
concurrency: int | None = None,
|
| 177 |
+
on_progress: Any = None,
|
| 178 |
+
) -> List[AnalysisResult]:
|
| 179 |
+
"""
|
| 180 |
+
Dávkové zpracování s omezenou souběžností (kvůli rate limitům).
|
| 181 |
+
|
| 182 |
+
``on_progress(done, total)`` je zavolán po dokončení každé zprávy,
|
| 183 |
+
stejná konvence jako ``pipeline.process_batch(on_progress=...)`` u
|
| 184 |
+
lokální větve - umožňuje hlásit průběh přes ``jobs.py`` i pro dávkové
|
| 185 |
+
zpracování LLM enginem.
|
| 186 |
+
"""
|
| 187 |
+
items = list(texts)
|
| 188 |
+
workers = concurrency or SETTINGS.concurrency
|
| 189 |
+
results: List[AnalysisResult] = [AnalysisResult()] * len(items)
|
| 190 |
+
done = 0
|
| 191 |
+
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
|
| 192 |
+
futures = {pool.submit(self.analyze, t): i for i, t in enumerate(items)}
|
| 193 |
+
for future in concurrent.futures.as_completed(futures):
|
| 194 |
+
results[futures[future]] = future.result()
|
| 195 |
+
done += 1
|
| 196 |
+
if on_progress:
|
| 197 |
+
on_progress(done, len(items))
|
| 198 |
+
return results
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def _fill_offsets(entities: List[Entity], text: str) -> None:
|
| 202 |
+
cursor = 0
|
| 203 |
+
for entity in entities:
|
| 204 |
+
if entity.start is not None and entity.end is not None:
|
| 205 |
+
continue
|
| 206 |
+
idx = text.find(entity.text, cursor)
|
| 207 |
+
if idx == -1:
|
| 208 |
+
idx = text.find(entity.text)
|
| 209 |
+
if idx != -1:
|
| 210 |
+
entity.start, entity.end = idx, idx + len(entity.text)
|
| 211 |
+
cursor = entity.end
|
llm_client/prompts.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Prompty a schéma strukturovaného výstupu.
|
| 3 |
+
|
| 4 |
+
Volný text z LLM je pro měření nepoužitelný. Výstup je proto vynucen
|
| 5 |
+
schématem: u Anthropic přes `tools` + `tool_choice`, u OpenAI přes
|
| 6 |
+
`response_format: json_schema`. Model tedy nemůže vrátit nic jiného než
|
| 7 |
+
validní objekt s pevně danými poli a povolenými hodnotami.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
from typing import Any, Dict, List
|
| 14 |
+
|
| 15 |
+
from .config import ENTITY_LABELS, PII_LABELS, SENTIMENT_LABELS, TOPIC_LABELS
|
| 16 |
+
|
| 17 |
+
TOOL_NAME = "record_analysis"
|
| 18 |
+
|
| 19 |
+
SYSTEM_PROMPT = """\
|
| 20 |
+
Jsi analytický nástroj pro zpracování zákaznických konverzací s podpůrnými \
|
| 21 |
+
službami. Analyzuješ jednu zprávu a vracíš strukturovaný výsledek.
|
| 22 |
+
|
| 23 |
+
Pravidla:
|
| 24 |
+
1. Používej výhradně hodnoty z povolených číselníků. Nevymýšlej nové třídy.
|
| 25 |
+
2. Sentiment posuzuj z pohledu pisatele zprávy, ne z pohledu operátora.
|
| 26 |
+
3. Entity vyznač přesně tak, jak se vyskytují v textu (doslovný podřetězec).
|
| 27 |
+
4. Skóre je tvoje míra jistoty v intervalu 0.0 až 1.0.
|
| 28 |
+
5. U témat vrať skóre pro všechna témata z číselníku, ne jen pro vítězné.
|
| 29 |
+
6. Pseudonymizovaný text vznikne nahrazením každého osobního údaje \
|
| 30 |
+
zástupným tokenem ve tvaru <TYP_N>, kde TYP je typ údaje a N je pořadové \
|
| 31 |
+
číslo výskytu daného typu (např. <PERSON_1>, <EMAIL_ADDRESS_1>). Stejná \
|
| 32 |
+
hodnota vyskytující se opakovaně dostane vždy stejný token.
|
| 33 |
+
7. Nepřidávej žádný komentář ani vysvětlení mimo strukturovaný výstup.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
USER_TEMPLATE = """\
|
| 37 |
+
Analyzuj následující zprávu.
|
| 38 |
+
|
| 39 |
+
<zprava>
|
| 40 |
+
{text}
|
| 41 |
+
</zprava>
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def build_input_schema() -> Dict[str, Any]:
|
| 46 |
+
"""JSON schéma vynuceného výstupu."""
|
| 47 |
+
return {
|
| 48 |
+
"type": "object",
|
| 49 |
+
"properties": {
|
| 50 |
+
"sentiment": {
|
| 51 |
+
"type": "object",
|
| 52 |
+
"properties": {
|
| 53 |
+
"label": {"type": "string", "enum": SENTIMENT_LABELS},
|
| 54 |
+
"score": {"type": "number", "minimum": 0, "maximum": 1},
|
| 55 |
+
},
|
| 56 |
+
"required": ["label", "score"],
|
| 57 |
+
},
|
| 58 |
+
"entities": {
|
| 59 |
+
"type": "array",
|
| 60 |
+
"items": {
|
| 61 |
+
"type": "object",
|
| 62 |
+
"properties": {
|
| 63 |
+
"text": {"type": "string"},
|
| 64 |
+
"label": {"type": "string", "enum": ENTITY_LABELS},
|
| 65 |
+
"score": {"type": "number", "minimum": 0, "maximum": 1},
|
| 66 |
+
},
|
| 67 |
+
"required": ["text", "label", "score"],
|
| 68 |
+
},
|
| 69 |
+
},
|
| 70 |
+
"topics": {
|
| 71 |
+
"type": "array",
|
| 72 |
+
"items": {
|
| 73 |
+
"type": "object",
|
| 74 |
+
"properties": {
|
| 75 |
+
"label": {"type": "string", "enum": TOPIC_LABELS},
|
| 76 |
+
"score": {"type": "number", "minimum": 0, "maximum": 1},
|
| 77 |
+
},
|
| 78 |
+
"required": ["label", "score"],
|
| 79 |
+
},
|
| 80 |
+
},
|
| 81 |
+
"pii": {
|
| 82 |
+
"type": "array",
|
| 83 |
+
"items": {
|
| 84 |
+
"type": "object",
|
| 85 |
+
"properties": {
|
| 86 |
+
"text": {"type": "string"},
|
| 87 |
+
"label": {"type": "string", "enum": PII_LABELS},
|
| 88 |
+
"placeholder": {"type": "string"},
|
| 89 |
+
},
|
| 90 |
+
"required": ["text", "label", "placeholder"],
|
| 91 |
+
},
|
| 92 |
+
},
|
| 93 |
+
"pseudonymized_text": {"type": "string"},
|
| 94 |
+
},
|
| 95 |
+
"required": ["sentiment", "entities", "topics", "pii", "pseudonymized_text"],
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def anthropic_tool() -> Dict[str, Any]:
|
| 100 |
+
return {
|
| 101 |
+
"name": TOOL_NAME,
|
| 102 |
+
"description": "Zaznamená výsledek analýzy jedné zprávy.",
|
| 103 |
+
"input_schema": build_input_schema(),
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def openai_response_format() -> Dict[str, Any]:
|
| 108 |
+
schema = build_input_schema()
|
| 109 |
+
_strictify(schema)
|
| 110 |
+
return {
|
| 111 |
+
"type": "json_schema",
|
| 112 |
+
"json_schema": {"name": TOOL_NAME, "strict": True, "schema": schema},
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _strictify(node: Any) -> None:
|
| 117 |
+
"""OpenAI strict mode vyžaduje additionalProperties=false u všech objektů."""
|
| 118 |
+
if isinstance(node, dict):
|
| 119 |
+
if node.get("type") == "object":
|
| 120 |
+
node["additionalProperties"] = False
|
| 121 |
+
node.setdefault("required", list(node.get("properties", {}).keys()))
|
| 122 |
+
for value in node.values():
|
| 123 |
+
_strictify(value)
|
| 124 |
+
elif isinstance(node, list):
|
| 125 |
+
for item in node:
|
| 126 |
+
_strictify(item)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def gemini_schema() -> Dict[str, Any]:
|
| 130 |
+
"""
|
| 131 |
+
Schéma pro Gemini `response_schema`. Gemini přijímá jen omezenou
|
| 132 |
+
podmnožinu JSON Schema (Google `Schema` proto) - na rozdíl od
|
| 133 |
+
Anthropic/OpenAI nezná klíče `minimum`/`maximum`, jejich přítomnost ve
|
| 134 |
+
schématu volání rovnou odmítne chybou "Unknown field for Schema:
|
| 135 |
+
minimum". Číselné rozmezí skóre (0.0-1.0) proto hlídá jen instrukce v
|
| 136 |
+
`SYSTEM_PROMPT`, ne schéma samotné.
|
| 137 |
+
"""
|
| 138 |
+
schema = build_input_schema()
|
| 139 |
+
_strip_unsupported_gemini_keys(schema)
|
| 140 |
+
return schema
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def _strip_unsupported_gemini_keys(node: Any) -> None:
|
| 144 |
+
if isinstance(node, dict):
|
| 145 |
+
node.pop("minimum", None)
|
| 146 |
+
node.pop("maximum", None)
|
| 147 |
+
for value in node.values():
|
| 148 |
+
_strip_unsupported_gemini_keys(value)
|
| 149 |
+
elif isinstance(node, list):
|
| 150 |
+
for item in node:
|
| 151 |
+
_strip_unsupported_gemini_keys(item)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def build_messages(text: str) -> List[Dict[str, str]]:
|
| 155 |
+
return [{"role": "user", "content": USER_TEMPLATE.format(text=text)}]
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def schema_fingerprint() -> str:
|
| 159 |
+
"""Otisk schématu – ukládá se k běhu kvůli reprodukovatelnosti."""
|
| 160 |
+
import hashlib
|
| 161 |
+
|
| 162 |
+
payload = json.dumps(build_input_schema(), sort_keys=True, ensure_ascii=False)
|
| 163 |
+
return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:12]
|
llm_client/schemas.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Datový kontrakt sdílený oběma enginy.
|
| 3 |
+
|
| 4 |
+
Klíčová myšlenka: BERT pipeline i LLM pipeline vracejí *stejnou* strukturu
|
| 5 |
+
`AnalysisResult`. Díky tomu je porovnání otázkou porovnání dvou instancí
|
| 6 |
+
téhož typu, nikoli ad-hoc mapování mezi nekompatibilními výstupy.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
from typing import Any, Dict, List, Optional
|
| 12 |
+
|
| 13 |
+
from pydantic import BaseModel, Field, field_validator
|
| 14 |
+
|
| 15 |
+
from .config import ENTITY_LABELS, PII_LABELS, SENTIMENT_LABELS, TOPIC_LABELS
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class Entity(BaseModel):
|
| 19 |
+
text: str
|
| 20 |
+
label: str
|
| 21 |
+
start: Optional[int] = None
|
| 22 |
+
end: Optional[int] = None
|
| 23 |
+
score: Optional[float] = None
|
| 24 |
+
|
| 25 |
+
@field_validator("label")
|
| 26 |
+
@classmethod
|
| 27 |
+
def _norm_label(cls, v: str) -> str:
|
| 28 |
+
v = v.strip().upper()
|
| 29 |
+
alias = {
|
| 30 |
+
"PERSON": "PER",
|
| 31 |
+
"PEOPLE": "PER",
|
| 32 |
+
"ORGANIZATION": "ORG",
|
| 33 |
+
"ORGANISATION": "ORG",
|
| 34 |
+
"LOCATION": "LOC",
|
| 35 |
+
"GPE": "LOC",
|
| 36 |
+
"PLACE": "LOC",
|
| 37 |
+
}
|
| 38 |
+
v = alias.get(v, v)
|
| 39 |
+
return v if v in ENTITY_LABELS else "MISC"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class TopicScore(BaseModel):
|
| 43 |
+
label: str
|
| 44 |
+
score: float = 0.0
|
| 45 |
+
|
| 46 |
+
@field_validator("label")
|
| 47 |
+
@classmethod
|
| 48 |
+
def _norm(cls, v: str) -> str:
|
| 49 |
+
v = v.strip().lower()
|
| 50 |
+
return v if v in TOPIC_LABELS else "other"
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class PIISpan(BaseModel):
|
| 54 |
+
text: str
|
| 55 |
+
label: str
|
| 56 |
+
start: Optional[int] = None
|
| 57 |
+
end: Optional[int] = None
|
| 58 |
+
placeholder: Optional[str] = None
|
| 59 |
+
|
| 60 |
+
@field_validator("label")
|
| 61 |
+
@classmethod
|
| 62 |
+
def _norm(cls, v: str) -> str:
|
| 63 |
+
v = v.strip().upper().replace(" ", "_")
|
| 64 |
+
alias = {"EMAIL": "EMAIL_ADDRESS", "PHONE": "PHONE_NUMBER", "NAME": "PERSON"}
|
| 65 |
+
v = alias.get(v, v)
|
| 66 |
+
return v if v in PII_LABELS else "ID_NUMBER"
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class Sentiment(BaseModel):
|
| 70 |
+
label: str = "neutral"
|
| 71 |
+
score: float = 0.0
|
| 72 |
+
|
| 73 |
+
@field_validator("label")
|
| 74 |
+
@classmethod
|
| 75 |
+
def _norm(cls, v: str) -> str:
|
| 76 |
+
v = v.strip().lower()
|
| 77 |
+
alias = {
|
| 78 |
+
"pos": "positive",
|
| 79 |
+
"neg": "negative",
|
| 80 |
+
"neu": "neutral",
|
| 81 |
+
"label_0": "negative",
|
| 82 |
+
"label_1": "neutral",
|
| 83 |
+
"label_2": "positive",
|
| 84 |
+
}
|
| 85 |
+
v = alias.get(v, v)
|
| 86 |
+
return v if v in SENTIMENT_LABELS else "neutral"
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class AnalysisResult(BaseModel):
|
| 90 |
+
"""Jednotný výstup jednoho enginu nad jednou zprávou."""
|
| 91 |
+
|
| 92 |
+
engine: str = "unknown" # 'bert' | 'llm'
|
| 93 |
+
provider: str = "local" # 'local' | 'anthropic' | 'openai'
|
| 94 |
+
model: str = ""
|
| 95 |
+
mode: str = "pre_pseudonymized"
|
| 96 |
+
|
| 97 |
+
sentiment: Sentiment = Field(default_factory=Sentiment)
|
| 98 |
+
entities: List[Entity] = Field(default_factory=list)
|
| 99 |
+
topics: List[TopicScore] = Field(default_factory=list)
|
| 100 |
+
pii: List[PIISpan] = Field(default_factory=list)
|
| 101 |
+
pseudonymized_text: str = ""
|
| 102 |
+
|
| 103 |
+
# provozní metriky
|
| 104 |
+
latency_ms: int = 0
|
| 105 |
+
tokens_in: int = 0
|
| 106 |
+
tokens_out: int = 0
|
| 107 |
+
cost_usd: float = 0.0
|
| 108 |
+
error: Optional[str] = None
|
| 109 |
+
raw_response: Optional[Dict[str, Any]] = None
|
| 110 |
+
|
| 111 |
+
@property
|
| 112 |
+
def top_topic(self) -> str:
|
| 113 |
+
if not self.topics:
|
| 114 |
+
return "other"
|
| 115 |
+
return max(self.topics, key=lambda t: t.score).label
|
main.py
CHANGED
|
@@ -8,10 +8,11 @@ Endpoints:
|
|
| 8 |
POST /predict -> sentiment only (backward compatible)
|
| 9 |
POST /ingest -> start a batch ingest job, returns a job id
|
| 10 |
GET /ingest/status/{id} -> progress / result of a background ingest job
|
| 11 |
-
GET /records -> recent stored (anonymized) records
|
| 12 |
-
GET /records/export -> stored records exported as XML, JSON or CSV
|
| 13 |
GET /stats -> aggregate statistics
|
| 14 |
GET /models -> default + suggested + currently loaded HF models per task
|
|
|
|
| 15 |
|
| 16 |
The full pipeline extracts named entities, classifies the topic, evaluates
|
| 17 |
sentiment, pseudonymizes the text and stores the structured result. Since V3,
|
|
@@ -21,6 +22,16 @@ built-in default model for that step. Since V4, stored records can be
|
|
| 21 |
exported in a choice of formats (XML, JSON, CSV) via `/records/export`. Since
|
| 22 |
V7, `/ingest` runs as a background job (see `jobs.py`) instead of one long
|
| 23 |
blocking request, so the dashboard can show a progress bar and elapsed timer.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
"""
|
| 25 |
|
| 26 |
from __future__ import annotations
|
|
@@ -30,6 +41,12 @@ import time
|
|
| 30 |
from pathlib import Path
|
| 31 |
from typing import Any
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
from fastapi import FastAPI, Form, HTTPException, UploadFile, File
|
| 34 |
from fastapi.responses import FileResponse, Response
|
| 35 |
from fastapi.staticfiles import StaticFiles
|
|
@@ -41,13 +58,18 @@ import jobs
|
|
| 41 |
from pipeline import process_message, process_batch
|
| 42 |
from processors import ner, topics, sentiment, anonymizer, model_registry
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
app = FastAPI(
|
| 45 |
title="Conversation Data Extraction System",
|
| 46 |
description=(
|
| 47 |
"Extracts named entities, topics and sentiment from chat conversations, "
|
| 48 |
"pseudonymizes personal data (GDPR) and stores structured results."
|
| 49 |
),
|
| 50 |
-
version="
|
| 51 |
)
|
| 52 |
|
| 53 |
BASE_DIR = Path(__file__).resolve().parent
|
|
@@ -87,6 +109,9 @@ class TextRequest(BaseModel):
|
|
| 87 |
sentiment_model: str | None = None
|
| 88 |
ner_model: str | None = None
|
| 89 |
topic_model: str | None = None
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
|
| 92 |
# ---------------------------------------------------------------------------
|
|
@@ -136,34 +161,117 @@ def list_models():
|
|
| 136 |
}
|
| 137 |
|
| 138 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
# ---------------------------------------------------------------------------
|
| 140 |
# Core analysis
|
| 141 |
# ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
@app.post("/analyze")
|
| 143 |
def analyze(payload: TextRequest):
|
| 144 |
"""Run the full pipeline on a single message and store the result."""
|
| 145 |
if not payload.text or not payload.text.strip():
|
| 146 |
raise HTTPException(status_code=400, detail="Text cannot be empty.")
|
| 147 |
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
try:
|
| 160 |
-
db.save_record(
|
| 161 |
except Exception as e:
|
| 162 |
print(f"[main] Failed to store record: {e}")
|
| 163 |
|
| 164 |
-
|
| 165 |
-
# we return both for the immediate UI, but only anonymized is persisted.
|
| 166 |
-
return result
|
| 167 |
|
| 168 |
|
| 169 |
@app.post("/predict")
|
|
@@ -191,6 +299,8 @@ async def ingest_file(
|
|
| 191 |
sentiment_model: str | None = Form(None),
|
| 192 |
ner_model: str | None = Form(None),
|
| 193 |
topic_model: str | None = Form(None),
|
|
|
|
|
|
|
| 194 |
):
|
| 195 |
"""
|
| 196 |
Start a background job that ingests a CSV or JSON file of conversations
|
|
@@ -201,6 +311,12 @@ async def ingest_file(
|
|
| 201 |
|
| 202 |
Parsing/validating the file happens synchronously here (fast, no model
|
| 203 |
calls); only the actual NLP processing runs in the background.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
"""
|
| 205 |
raw = await file.read()
|
| 206 |
if not raw:
|
|
@@ -225,6 +341,10 @@ async def ingest_file(
|
|
| 225 |
job_id = jobs.create_job(total=len(messages))
|
| 226 |
|
| 227 |
def run_job() -> None:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
try:
|
| 229 |
results = process_batch(
|
| 230 |
messages,
|
|
@@ -249,6 +369,7 @@ async def ingest_file(
|
|
| 249 |
print(f"[main] Failed to store ingest record: {e}")
|
| 250 |
|
| 251 |
jobs.finish_job(job_id, {
|
|
|
|
| 252 |
"received": len(messages),
|
| 253 |
"processed": len(results),
|
| 254 |
"stored": stored,
|
|
@@ -256,14 +377,67 @@ async def ingest_file(
|
|
| 256 |
"items": results,
|
| 257 |
})
|
| 258 |
|
| 259 |
-
# Runs the (blocking, CPU-bound)
|
| 260 |
-
# an asyncio task, so it doesn't block the event loop and
|
| 261 |
-
# keep being served while it runs.
|
| 262 |
threading.Thread(target=run_job, daemon=True).start()
|
| 263 |
|
| 264 |
return {"job_id": job_id, "total": len(messages)}
|
| 265 |
|
| 266 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 267 |
@app.get("/ingest/status/{job_id}")
|
| 268 |
def ingest_status(job_id: str):
|
| 269 |
"""
|
|
@@ -297,20 +471,60 @@ def ingest_status(job_id: str):
|
|
| 297 |
# ---------------------------------------------------------------------------
|
| 298 |
# Stored data
|
| 299 |
# ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
@app.get("/records")
|
| 301 |
-
def records(
|
| 302 |
-
|
| 303 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
|
| 305 |
|
| 306 |
@app.get("/records/export")
|
| 307 |
-
def export_records(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
"""
|
| 309 |
Export stored (anonymized) records. ``format`` is one of the keys in
|
| 310 |
``db.EXPORT_FORMATS`` (currently ``xml``, ``json``, ``csv``).
|
|
|
|
|
|
|
| 311 |
"""
|
|
|
|
| 312 |
try:
|
| 313 |
-
content, media_type = db.export_records(
|
|
|
|
|
|
|
| 314 |
except ValueError as e:
|
| 315 |
raise HTTPException(status_code=400, detail=str(e))
|
| 316 |
|
|
|
|
| 8 |
POST /predict -> sentiment only (backward compatible)
|
| 9 |
POST /ingest -> start a batch ingest job, returns a job id
|
| 10 |
GET /ingest/status/{id} -> progress / result of a background ingest job
|
| 11 |
+
GET /records -> recent stored (anonymized) records, optional ?engine=local|llm
|
| 12 |
+
GET /records/export -> stored records exported as XML, JSON or CSV, optional ?engine=
|
| 13 |
GET /stats -> aggregate statistics
|
| 14 |
GET /models -> default + suggested + currently loaded HF models per task
|
| 15 |
+
GET /engines -> local pipeline + configured LLM providers (V8)
|
| 16 |
|
| 17 |
The full pipeline extracts named entities, classifies the topic, evaluates
|
| 18 |
sentiment, pseudonymizes the text and stores the structured result. Since V3,
|
|
|
|
| 22 |
exported in a choice of formats (XML, JSON, CSV) via `/records/export`. Since
|
| 23 |
V7, `/ingest` runs as a background job (see `jobs.py`) instead of one long
|
| 24 |
blocking request, so the dashboard can show a progress bar and elapsed timer.
|
| 25 |
+
|
| 26 |
+
Since V8, `/analyze` and `/ingest` accept an `engine` field: `"local"` (the
|
| 27 |
+
default, unchanged BERT pipeline above) or the name of a configured LLM
|
| 28 |
+
provider (`"anthropic"`, `"google"`, `"openai"`) - see `llm_client/`. In LLM
|
| 29 |
+
mode, the same local anonymization runs first (pre_pseudonymized mode), and
|
| 30 |
+
the pseudonymized text is what actually leaves the system; a single LLM call
|
| 31 |
+
then determines sentiment, entities and topic together. LLM results are
|
| 32 |
+
mapped onto the same shape as the local pipeline's and stored in the same
|
| 33 |
+
`records` table (see `db.save_record`), so they show up in `/records` and
|
| 34 |
+
the dashboard next to local-model results, tagged with `engine`/`provider`.
|
| 35 |
"""
|
| 36 |
|
| 37 |
from __future__ import annotations
|
|
|
|
| 41 |
from pathlib import Path
|
| 42 |
from typing import Any
|
| 43 |
|
| 44 |
+
from dotenv import load_dotenv
|
| 45 |
+
|
| 46 |
+
# Must run before importing llm_client: ProviderConfig/PROVIDERS read the
|
| 47 |
+
# LLM API key env vars at import time, so .env has to be loaded first.
|
| 48 |
+
load_dotenv()
|
| 49 |
+
|
| 50 |
from fastapi import FastAPI, Form, HTTPException, UploadFile, File
|
| 51 |
from fastapi.responses import FileResponse, Response
|
| 52 |
from fastapi.staticfiles import StaticFiles
|
|
|
|
| 58 |
from pipeline import process_message, process_batch
|
| 59 |
from processors import ner, topics, sentiment, anonymizer, model_registry
|
| 60 |
|
| 61 |
+
from llm_client.client import LLMError
|
| 62 |
+
from llm_client.config import PROVIDERS as LLM_PROVIDERS
|
| 63 |
+
from llm_client.pipeline import LLMPipeline
|
| 64 |
+
from llm_client.schemas import AnalysisResult
|
| 65 |
+
|
| 66 |
app = FastAPI(
|
| 67 |
title="Conversation Data Extraction System",
|
| 68 |
description=(
|
| 69 |
"Extracts named entities, topics and sentiment from chat conversations, "
|
| 70 |
"pseudonymizes personal data (GDPR) and stores structured results."
|
| 71 |
),
|
| 72 |
+
version="8.0.0",
|
| 73 |
)
|
| 74 |
|
| 75 |
BASE_DIR = Path(__file__).resolve().parent
|
|
|
|
| 109 |
sentiment_model: str | None = None
|
| 110 |
ner_model: str | None = None
|
| 111 |
topic_model: str | None = None
|
| 112 |
+
# V8: "local" (default) or a configured LLM provider name (see /engines).
|
| 113 |
+
engine: str = "local"
|
| 114 |
+
llm_mode: str | None = None
|
| 115 |
|
| 116 |
|
| 117 |
# ---------------------------------------------------------------------------
|
|
|
|
| 161 |
}
|
| 162 |
|
| 163 |
|
| 164 |
+
@app.get("/engines")
|
| 165 |
+
def list_engines():
|
| 166 |
+
"""
|
| 167 |
+
Available analysis engines: the local BERT pipeline (always available)
|
| 168 |
+
plus any LLM provider that has an API key configured (see
|
| 169 |
+
`llm_client/config.py` / `.env.example`). The dashboard uses this to
|
| 170 |
+
build the Engine selector - providers without a key are reported but
|
| 171 |
+
marked `available: false` so the UI can grey them out.
|
| 172 |
+
"""
|
| 173 |
+
engines = [{"id": "local", "label": "Lokální modely (BERT)", "available": True}]
|
| 174 |
+
for name, cfg in LLM_PROVIDERS.items():
|
| 175 |
+
engines.append(
|
| 176 |
+
{
|
| 177 |
+
"id": name,
|
| 178 |
+
"label": f"LLM: {name}",
|
| 179 |
+
"model": cfg.model,
|
| 180 |
+
"available": cfg.available,
|
| 181 |
+
}
|
| 182 |
+
)
|
| 183 |
+
return {"engines": engines}
|
| 184 |
+
|
| 185 |
+
|
| 186 |
# ---------------------------------------------------------------------------
|
| 187 |
# Core analysis
|
| 188 |
# ---------------------------------------------------------------------------
|
| 189 |
+
def _llm_result_to_response(original_text: str, result: AnalysisResult) -> dict[str, Any]:
|
| 190 |
+
"""
|
| 191 |
+
Map an `llm_client` `AnalysisResult` onto the same response shape
|
| 192 |
+
`/analyze` already returns for the local engine, so it can be stored via
|
| 193 |
+
the same `db.save_record` and listed/exported alongside local-model
|
| 194 |
+
records. Adds engine/provider/model/latency/cost on top, which the
|
| 195 |
+
local-engine response doesn't have (those columns stay `NULL` for it).
|
| 196 |
+
"""
|
| 197 |
+
top = max(result.topics, key=lambda t: t.score, default=None)
|
| 198 |
+
entities = [
|
| 199 |
+
{
|
| 200 |
+
"text": e.text,
|
| 201 |
+
"type": e.label,
|
| 202 |
+
"start": e.start,
|
| 203 |
+
"end": e.end,
|
| 204 |
+
"score": e.score,
|
| 205 |
+
}
|
| 206 |
+
for e in result.entities
|
| 207 |
+
]
|
| 208 |
+
return {
|
| 209 |
+
"text": original_text,
|
| 210 |
+
"anonymized_text": result.pseudonymized_text,
|
| 211 |
+
"entities": entities,
|
| 212 |
+
"topic": top.label if top else None,
|
| 213 |
+
"topic_score": top.score if top else 0.0,
|
| 214 |
+
"topic_candidates": [t.model_dump() for t in result.topics],
|
| 215 |
+
"sentiment": result.sentiment.label,
|
| 216 |
+
"sentiment_score": result.sentiment.score,
|
| 217 |
+
"engine": result.engine,
|
| 218 |
+
"provider": result.provider,
|
| 219 |
+
"model": result.model,
|
| 220 |
+
"latency_ms": result.latency_ms,
|
| 221 |
+
"cost_usd": result.cost_usd,
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def _get_llm_pipeline(engine: str, llm_mode: str | None) -> LLMPipeline:
|
| 226 |
+
try:
|
| 227 |
+
return LLMPipeline(provider=engine, mode=llm_mode or "pre_pseudonymized")
|
| 228 |
+
except (LLMError, ValueError) as e:
|
| 229 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 230 |
+
|
| 231 |
+
|
| 232 |
@app.post("/analyze")
|
| 233 |
def analyze(payload: TextRequest):
|
| 234 |
"""Run the full pipeline on a single message and store the result."""
|
| 235 |
if not payload.text or not payload.text.strip():
|
| 236 |
raise HTTPException(status_code=400, detail="Text cannot be empty.")
|
| 237 |
|
| 238 |
+
if payload.engine == "local":
|
| 239 |
+
try:
|
| 240 |
+
result = process_message(
|
| 241 |
+
payload.text,
|
| 242 |
+
topic_labels=payload.topic_labels,
|
| 243 |
+
sentiment_model=payload.sentiment_model,
|
| 244 |
+
ner_model=payload.ner_model,
|
| 245 |
+
topic_model=payload.topic_model,
|
| 246 |
+
)
|
| 247 |
+
except RuntimeError as e:
|
| 248 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 249 |
+
|
| 250 |
+
try:
|
| 251 |
+
db.save_record(result, source="single")
|
| 252 |
+
except Exception as e:
|
| 253 |
+
print(f"[main] Failed to store record: {e}")
|
| 254 |
+
|
| 255 |
+
# do not return the raw text in a way that encourages storing it client-side;
|
| 256 |
+
# we return both for the immediate UI, but only anonymized is persisted.
|
| 257 |
+
return result
|
| 258 |
+
|
| 259 |
+
# LLM engine: local anonymization happens inside LLMPipeline.analyze()
|
| 260 |
+
# (same processors.anonymizer as the local engine) before the
|
| 261 |
+
# pseudonymized text is sent to the chosen provider in a single call.
|
| 262 |
+
llm_pipeline = _get_llm_pipeline(payload.engine, payload.llm_mode)
|
| 263 |
+
result = llm_pipeline.analyze(payload.text)
|
| 264 |
+
if result.error:
|
| 265 |
+
raise HTTPException(status_code=502, detail=result.error)
|
| 266 |
+
|
| 267 |
+
response = _llm_result_to_response(payload.text, result)
|
| 268 |
|
| 269 |
try:
|
| 270 |
+
db.save_record(response, source="single")
|
| 271 |
except Exception as e:
|
| 272 |
print(f"[main] Failed to store record: {e}")
|
| 273 |
|
| 274 |
+
return response
|
|
|
|
|
|
|
| 275 |
|
| 276 |
|
| 277 |
@app.post("/predict")
|
|
|
|
| 299 |
sentiment_model: str | None = Form(None),
|
| 300 |
ner_model: str | None = Form(None),
|
| 301 |
topic_model: str | None = Form(None),
|
| 302 |
+
engine: str = Form("local"),
|
| 303 |
+
llm_mode: str | None = Form(None),
|
| 304 |
):
|
| 305 |
"""
|
| 306 |
Start a background job that ingests a CSV or JSON file of conversations
|
|
|
|
| 311 |
|
| 312 |
Parsing/validating the file happens synchronously here (fast, no model
|
| 313 |
calls); only the actual NLP processing runs in the background.
|
| 314 |
+
|
| 315 |
+
Since V8, ``engine`` selects "local" (default, unchanged) or a
|
| 316 |
+
configured LLM provider name. LLM batches are processed with bounded
|
| 317 |
+
concurrency via `LLMPipeline.analyze_batch` (local anonymization first,
|
| 318 |
+
as always) and stored in the same `records` table as local-model
|
| 319 |
+
results; progress is still reported through the same job mechanism.
|
| 320 |
"""
|
| 321 |
raw = await file.read()
|
| 322 |
if not raw:
|
|
|
|
| 341 |
job_id = jobs.create_job(total=len(messages))
|
| 342 |
|
| 343 |
def run_job() -> None:
|
| 344 |
+
if engine != "local":
|
| 345 |
+
_run_llm_ingest_job(job_id, messages, engine, llm_mode, truncated)
|
| 346 |
+
return
|
| 347 |
+
|
| 348 |
try:
|
| 349 |
results = process_batch(
|
| 350 |
messages,
|
|
|
|
| 369 |
print(f"[main] Failed to store ingest record: {e}")
|
| 370 |
|
| 371 |
jobs.finish_job(job_id, {
|
| 372 |
+
"engine": "local",
|
| 373 |
"received": len(messages),
|
| 374 |
"processed": len(results),
|
| 375 |
"stored": stored,
|
|
|
|
| 377 |
"items": results,
|
| 378 |
})
|
| 379 |
|
| 380 |
+
# Runs the (blocking, CPU-bound or network-bound) work in a plain thread
|
| 381 |
+
# rather than an asyncio task, so it doesn't block the event loop and
|
| 382 |
+
# status polls keep being served while it runs.
|
| 383 |
threading.Thread(target=run_job, daemon=True).start()
|
| 384 |
|
| 385 |
return {"job_id": job_id, "total": len(messages)}
|
| 386 |
|
| 387 |
|
| 388 |
+
def _run_llm_ingest_job(
|
| 389 |
+
job_id: str,
|
| 390 |
+
messages: list[dict[str, Any]],
|
| 391 |
+
engine: str,
|
| 392 |
+
llm_mode: str | None,
|
| 393 |
+
truncated: bool,
|
| 394 |
+
) -> None:
|
| 395 |
+
"""
|
| 396 |
+
LLM-engine counterpart of the local `/ingest` job body. Runs
|
| 397 |
+
`LLMPipeline.analyze_batch` (bounded concurrency, local anonymization
|
| 398 |
+
first as always) and stores each result via the same `db.save_record`
|
| 399 |
+
used by the local engine, so LLM-analyzed messages show up in `/records`
|
| 400 |
+
next to local-model ones instead of in a separate database.
|
| 401 |
+
"""
|
| 402 |
+
try:
|
| 403 |
+
llm_pipeline = LLMPipeline(provider=engine, mode=llm_mode or "pre_pseudonymized")
|
| 404 |
+
except (LLMError, ValueError) as e:
|
| 405 |
+
jobs.fail_job(job_id, str(e))
|
| 406 |
+
return
|
| 407 |
+
|
| 408 |
+
texts = [(m.get("text") or "").strip() for m in messages if (m.get("text") or "").strip()]
|
| 409 |
+
update_progress = jobs.progress_callback(job_id)
|
| 410 |
+
|
| 411 |
+
try:
|
| 412 |
+
results = llm_pipeline.analyze_batch(
|
| 413 |
+
texts, on_progress=lambda done, _total: update_progress(done)
|
| 414 |
+
)
|
| 415 |
+
except Exception as e: # pragma: no cover - safety net so a job never hangs
|
| 416 |
+
jobs.fail_job(job_id, f"Unexpected error: {e}")
|
| 417 |
+
return
|
| 418 |
+
|
| 419 |
+
responses = [_llm_result_to_response(text, r) for text, r in zip(texts, results)]
|
| 420 |
+
failed = sum(1 for r in results if r.error)
|
| 421 |
+
|
| 422 |
+
stored = 0
|
| 423 |
+
for response in responses:
|
| 424 |
+
try:
|
| 425 |
+
db.save_record(response, source="ingest")
|
| 426 |
+
stored += 1
|
| 427 |
+
except Exception as e:
|
| 428 |
+
print(f"[main] Failed to store LLM ingest record: {e}")
|
| 429 |
+
|
| 430 |
+
jobs.finish_job(job_id, {
|
| 431 |
+
"engine": engine,
|
| 432 |
+
"received": len(messages),
|
| 433 |
+
"processed": len(responses) - failed,
|
| 434 |
+
"failed": failed,
|
| 435 |
+
"stored": stored,
|
| 436 |
+
"truncated": truncated,
|
| 437 |
+
"items": responses,
|
| 438 |
+
})
|
| 439 |
+
|
| 440 |
+
|
| 441 |
@app.get("/ingest/status/{job_id}")
|
| 442 |
def ingest_status(job_id: str):
|
| 443 |
"""
|
|
|
|
| 471 |
# ---------------------------------------------------------------------------
|
| 472 |
# Stored data
|
| 473 |
# ---------------------------------------------------------------------------
|
| 474 |
+
def _validate_engine_filter(engine: str | None) -> str | None:
|
| 475 |
+
"""
|
| 476 |
+
Shared validation for the ``engine`` filter on ``/records`` and
|
| 477 |
+
``/records/export``: ``"local"`` (BERT pipeline), ``"llm"`` (any
|
| 478 |
+
provider), or omitted/``None`` for both.
|
| 479 |
+
"""
|
| 480 |
+
if engine is not None and engine not in ("local", "llm"):
|
| 481 |
+
raise HTTPException(
|
| 482 |
+
status_code=400,
|
| 483 |
+
detail="Invalid 'engine' filter. Use 'local', 'llm', or omit it for both.",
|
| 484 |
+
)
|
| 485 |
+
return engine
|
| 486 |
+
|
| 487 |
+
|
| 488 |
@app.get("/records")
|
| 489 |
+
def records(
|
| 490 |
+
limit: int = 100,
|
| 491 |
+
engine: str | None = None,
|
| 492 |
+
topic: str | None = None,
|
| 493 |
+
sentiment: str | None = None,
|
| 494 |
+
):
|
| 495 |
+
"""
|
| 496 |
+
Return recent stored records (anonymized only).
|
| 497 |
+
|
| 498 |
+
``engine`` optionally filters to ``"local"`` (BERT pipeline) or
|
| 499 |
+
``"llm"`` (any provider). ``topic``/``sentiment`` optionally filter to
|
| 500 |
+
an exact label (see ``GET /stats`` for the labels actually in use - a
|
| 501 |
+
custom sentiment/topic model can in principle produce others, so these
|
| 502 |
+
aren't restricted to a fixed set). Any combination may be used together;
|
| 503 |
+
omitted filters simply don't narrow the result.
|
| 504 |
+
"""
|
| 505 |
+
engine = _validate_engine_filter(engine)
|
| 506 |
+
return db.get_records(limit=limit, engine=engine, topic=topic, sentiment=sentiment)
|
| 507 |
|
| 508 |
|
| 509 |
@app.get("/records/export")
|
| 510 |
+
def export_records(
|
| 511 |
+
format: str = "xml",
|
| 512 |
+
limit: int | None = None,
|
| 513 |
+
engine: str | None = None,
|
| 514 |
+
topic: str | None = None,
|
| 515 |
+
sentiment: str | None = None,
|
| 516 |
+
):
|
| 517 |
"""
|
| 518 |
Export stored (anonymized) records. ``format`` is one of the keys in
|
| 519 |
``db.EXPORT_FORMATS`` (currently ``xml``, ``json``, ``csv``).
|
| 520 |
+
``engine``/``topic``/``sentiment`` optionally filter, same as
|
| 521 |
+
``/records``.
|
| 522 |
"""
|
| 523 |
+
engine = _validate_engine_filter(engine)
|
| 524 |
try:
|
| 525 |
+
content, media_type = db.export_records(
|
| 526 |
+
format, limit=limit, engine=engine, topic=topic, sentiment=sentiment
|
| 527 |
+
)
|
| 528 |
except ValueError as e:
|
| 529 |
raise HTTPException(status_code=400, detail=str(e))
|
| 530 |
|
requirements.txt
CHANGED
|
@@ -6,3 +6,9 @@ torch
|
|
| 6 |
presidio-analyzer
|
| 7 |
presidio-anonymizer
|
| 8 |
spacy
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
presidio-analyzer
|
| 7 |
presidio-anonymizer
|
| 8 |
spacy
|
| 9 |
+
|
| 10 |
+
# volitelná LLM větev (Claude / Gemini / OpenAI) - viz llm_client/ a .env.example
|
| 11 |
+
anthropic
|
| 12 |
+
openai
|
| 13 |
+
google-generativeai
|
| 14 |
+
python-dotenv
|
static/app.js
CHANGED
|
@@ -9,6 +9,12 @@ const entitiesEl = document.getElementById("entities");
|
|
| 9 |
const anonEl = document.getElementById("anon");
|
| 10 |
const errorEl = document.getElementById("error");
|
| 11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
const fileEl = document.getElementById("file");
|
| 13 |
const ingestBtn = document.getElementById("ingestBtn");
|
| 14 |
const ingestStatusEl = document.getElementById("ingestStatus");
|
|
@@ -103,6 +109,54 @@ async function loadModelPickers() {
|
|
| 103 |
}
|
| 104 |
}
|
| 105 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
function setStatus(msg) {
|
| 107 |
statusEl.textContent = msg || "";
|
| 108 |
}
|
|
@@ -119,6 +173,19 @@ function sentimentClass(label) {
|
|
| 119 |
}
|
| 120 |
|
| 121 |
function renderResult(data) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
// sentiment
|
| 123 |
const sLabel = data.sentiment ?? "—";
|
| 124 |
const sScore =
|
|
@@ -168,9 +235,11 @@ async function analyze() {
|
|
| 168 |
analyzeBtn.disabled = true;
|
| 169 |
setStatus("Analyzing…");
|
| 170 |
|
| 171 |
-
const
|
| 172 |
-
const
|
| 173 |
-
const
|
|
|
|
|
|
|
| 174 |
|
| 175 |
try {
|
| 176 |
const res = await fetch("/analyze", {
|
|
@@ -178,6 +247,7 @@ async function analyze() {
|
|
| 178 |
headers: { "Content-Type": "application/json" },
|
| 179 |
body: JSON.stringify({
|
| 180 |
text,
|
|
|
|
| 181 |
sentiment_model: sentimentModel,
|
| 182 |
ner_model: nerModel,
|
| 183 |
topic_model: topicModel,
|
|
@@ -284,12 +354,16 @@ async function ingest() {
|
|
| 284 |
try {
|
| 285 |
const form = new FormData();
|
| 286 |
form.append("file", file);
|
| 287 |
-
const
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
const res = await fetch("/ingest", { method: "POST", body: form });
|
| 294 |
const data = await res.json().catch(() => null);
|
| 295 |
if (!res.ok) {
|
|
@@ -322,3 +396,4 @@ textEl.addEventListener("keydown", (e) => {
|
|
| 322 |
ingestBtn.addEventListener("click", ingest);
|
| 323 |
|
| 324 |
loadModelPickers();
|
|
|
|
|
|
| 9 |
const anonEl = document.getElementById("anon");
|
| 10 |
const errorEl = document.getElementById("error");
|
| 11 |
|
| 12 |
+
const engineSelectEl = document.getElementById("engineSelect");
|
| 13 |
+
const llmEngineNoteEl = document.getElementById("llmEngineNote");
|
| 14 |
+
const modelPickersEl = document.querySelector(".modelPickers");
|
| 15 |
+
const engineRowEl = document.getElementById("engineRow");
|
| 16 |
+
const engineInfoEl = document.getElementById("engineInfo");
|
| 17 |
+
|
| 18 |
const fileEl = document.getElementById("file");
|
| 19 |
const ingestBtn = document.getElementById("ingestBtn");
|
| 20 |
const ingestStatusEl = document.getElementById("ingestStatus");
|
|
|
|
| 109 |
}
|
| 110 |
}
|
| 111 |
|
| 112 |
+
// ---------------------------------------------------------------------------
|
| 113 |
+
// Engine selector: "local" (BERT pipeline, existing 3 model dropdowns) or
|
| 114 |
+
// one of the configured LLM providers (single call determines sentiment,
|
| 115 |
+
// entities and topic together; the 3 dropdowns are hidden in that case).
|
| 116 |
+
// ---------------------------------------------------------------------------
|
| 117 |
+
function isLocalEngine() {
|
| 118 |
+
return !engineSelectEl || engineSelectEl.value === "local";
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
function applyEngineVisibility() {
|
| 122 |
+
const local = isLocalEngine();
|
| 123 |
+
if (modelPickersEl) modelPickersEl.hidden = !local;
|
| 124 |
+
if (llmEngineNoteEl) llmEngineNoteEl.hidden = local;
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
async function loadEngines() {
|
| 128 |
+
if (!engineSelectEl) return;
|
| 129 |
+
engineSelectEl.innerHTML = "";
|
| 130 |
+
|
| 131 |
+
let engines = [{ id: "local", label: "Lokální modely (BERT)", available: true }];
|
| 132 |
+
try {
|
| 133 |
+
const res = await fetch("/engines");
|
| 134 |
+
if (res.ok) {
|
| 135 |
+
const data = await res.json();
|
| 136 |
+
if (Array.isArray(data?.engines) && data.engines.length) {
|
| 137 |
+
engines = data.engines;
|
| 138 |
+
}
|
| 139 |
+
}
|
| 140 |
+
} catch (e) {
|
| 141 |
+
// fall back to local-only option above
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
for (const engine of engines) {
|
| 145 |
+
const opt = document.createElement("option");
|
| 146 |
+
opt.value = engine.id;
|
| 147 |
+
opt.textContent = engine.available === false ? `${engine.label} (chybí API klíč)` : engine.label;
|
| 148 |
+
opt.disabled = engine.available === false;
|
| 149 |
+
engineSelectEl.appendChild(opt);
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
engineSelectEl.value = "local";
|
| 153 |
+
applyEngineVisibility();
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
if (engineSelectEl) {
|
| 157 |
+
engineSelectEl.addEventListener("change", applyEngineVisibility);
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
function setStatus(msg) {
|
| 161 |
statusEl.textContent = msg || "";
|
| 162 |
}
|
|
|
|
| 173 |
}
|
| 174 |
|
| 175 |
function renderResult(data) {
|
| 176 |
+
// engine (only present when an LLM engine was used)
|
| 177 |
+
if (data.engine && data.engine !== "local") {
|
| 178 |
+
const parts = [data.provider || data.engine];
|
| 179 |
+
if (data.model) parts.push(data.model);
|
| 180 |
+
if (typeof data.latency_ms === "number") parts.push(`${data.latency_ms} ms`);
|
| 181 |
+
if (typeof data.cost_usd === "number") parts.push(`$${data.cost_usd.toFixed(4)}`);
|
| 182 |
+
engineInfoEl.textContent = parts.join(" · ");
|
| 183 |
+
engineRowEl.hidden = false;
|
| 184 |
+
} else {
|
| 185 |
+
engineInfoEl.textContent = "";
|
| 186 |
+
engineRowEl.hidden = true;
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
// sentiment
|
| 190 |
const sLabel = data.sentiment ?? "—";
|
| 191 |
const sScore =
|
|
|
|
| 235 |
analyzeBtn.disabled = true;
|
| 236 |
setStatus("Analyzing…");
|
| 237 |
|
| 238 |
+
const engine = engineSelectEl ? engineSelectEl.value : "local";
|
| 239 |
+
const local = isLocalEngine();
|
| 240 |
+
const sentimentModel = local ? modelPickers.sentiment?.getValue() ?? null : null;
|
| 241 |
+
const nerModel = local ? modelPickers.ner?.getValue() ?? null : null;
|
| 242 |
+
const topicModel = local ? modelPickers.topics?.getValue() ?? null : null;
|
| 243 |
|
| 244 |
try {
|
| 245 |
const res = await fetch("/analyze", {
|
|
|
|
| 247 |
headers: { "Content-Type": "application/json" },
|
| 248 |
body: JSON.stringify({
|
| 249 |
text,
|
| 250 |
+
engine,
|
| 251 |
sentiment_model: sentimentModel,
|
| 252 |
ner_model: nerModel,
|
| 253 |
topic_model: topicModel,
|
|
|
|
| 354 |
try {
|
| 355 |
const form = new FormData();
|
| 356 |
form.append("file", file);
|
| 357 |
+
const engine = engineSelectEl ? engineSelectEl.value : "local";
|
| 358 |
+
form.append("engine", engine);
|
| 359 |
+
if (isLocalEngine()) {
|
| 360 |
+
const sentimentModel = modelPickers.sentiment?.getValue();
|
| 361 |
+
const nerModel = modelPickers.ner?.getValue();
|
| 362 |
+
const topicModel = modelPickers.topics?.getValue();
|
| 363 |
+
if (sentimentModel) form.append("sentiment_model", sentimentModel);
|
| 364 |
+
if (nerModel) form.append("ner_model", nerModel);
|
| 365 |
+
if (topicModel) form.append("topic_model", topicModel);
|
| 366 |
+
}
|
| 367 |
const res = await fetch("/ingest", { method: "POST", body: form });
|
| 368 |
const data = await res.json().catch(() => null);
|
| 369 |
if (!res.ok) {
|
|
|
|
| 396 |
ingestBtn.addEventListener("click", ingest);
|
| 397 |
|
| 398 |
loadModelPickers();
|
| 399 |
+
loadEngines();
|
static/index.html
CHANGED
|
@@ -16,6 +16,17 @@
|
|
| 16 |
</p>
|
| 17 |
</header>
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
<!-- Single message analysis -->
|
| 20 |
<section class="card">
|
| 21 |
<label class="label" for="text">Message</label>
|
|
@@ -47,6 +58,10 @@
|
|
| 47 |
</div>
|
| 48 |
|
| 49 |
<div id="result" class="result" hidden>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
<div class="resultRow">
|
| 51 |
<span class="k">Sentiment</span>
|
| 52 |
<span id="sentiment" class="v"></span>
|
|
|
|
| 16 |
</p>
|
| 17 |
</header>
|
| 18 |
|
| 19 |
+
<!-- Engine: local BERT pipeline, or a configured LLM provider -->
|
| 20 |
+
<section class="card">
|
| 21 |
+
<span class="label">Engine</span>
|
| 22 |
+
<select id="engineSelect" class="modelSelect"></select>
|
| 23 |
+
<p id="llmEngineNote" class="sub small" hidden>
|
| 24 |
+
Anonymizace probíhá lokálně stejně jako u lokálních modelů, ještě
|
| 25 |
+
předtím, než se pseudonymizovaný text pošle přes API. Sentiment,
|
| 26 |
+
entity i téma pak jedním voláním určí zvolený model.
|
| 27 |
+
</p>
|
| 28 |
+
</section>
|
| 29 |
+
|
| 30 |
<!-- Single message analysis -->
|
| 31 |
<section class="card">
|
| 32 |
<label class="label" for="text">Message</label>
|
|
|
|
| 58 |
</div>
|
| 59 |
|
| 60 |
<div id="result" class="result" hidden>
|
| 61 |
+
<div id="engineRow" class="resultRow" hidden>
|
| 62 |
+
<span class="k">Engine</span>
|
| 63 |
+
<span id="engineInfo" class="v"></span>
|
| 64 |
+
</div>
|
| 65 |
<div class="resultRow">
|
| 66 |
<span class="k">Sentiment</span>
|
| 67 |
<span id="sentiment" class="v"></span>
|
static/records.html
CHANGED
|
@@ -24,6 +24,29 @@
|
|
| 24 |
<div class="row">
|
| 25 |
<button id="reloadBtn" class="btn" type="button">Reload</button>
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
<div class="dropdown" id="exportDropdown">
|
| 28 |
<button
|
| 29 |
id="exportBtn"
|
|
@@ -53,6 +76,7 @@
|
|
| 53 |
<th>Topic</th>
|
| 54 |
<th>Sentiment</th>
|
| 55 |
<th>Entities</th>
|
|
|
|
| 56 |
<th>Source</th>
|
| 57 |
</tr>
|
| 58 |
</thead>
|
|
|
|
| 24 |
<div class="row">
|
| 25 |
<button id="reloadBtn" class="btn" type="button">Reload</button>
|
| 26 |
|
| 27 |
+
<label class="row" style="gap: 6px">
|
| 28 |
+
<span class="label" style="margin: 0">Engine</span>
|
| 29 |
+
<select id="engineFilter" class="modelSelect">
|
| 30 |
+
<option value="">All</option>
|
| 31 |
+
<option value="local">Local (BERT)</option>
|
| 32 |
+
<option value="llm">LLM</option>
|
| 33 |
+
</select>
|
| 34 |
+
</label>
|
| 35 |
+
|
| 36 |
+
<label class="row" style="gap: 6px">
|
| 37 |
+
<span class="label" style="margin: 0">Topic</span>
|
| 38 |
+
<select id="topicFilter" class="modelSelect">
|
| 39 |
+
<option value="">All</option>
|
| 40 |
+
</select>
|
| 41 |
+
</label>
|
| 42 |
+
|
| 43 |
+
<label class="row" style="gap: 6px">
|
| 44 |
+
<span class="label" style="margin: 0">Sentiment</span>
|
| 45 |
+
<select id="sentimentFilter" class="modelSelect">
|
| 46 |
+
<option value="">All</option>
|
| 47 |
+
</select>
|
| 48 |
+
</label>
|
| 49 |
+
|
| 50 |
<div class="dropdown" id="exportDropdown">
|
| 51 |
<button
|
| 52 |
id="exportBtn"
|
|
|
|
| 76 |
<th>Topic</th>
|
| 77 |
<th>Sentiment</th>
|
| 78 |
<th>Entities</th>
|
| 79 |
+
<th>Engine</th>
|
| 80 |
<th>Source</th>
|
| 81 |
</tr>
|
| 82 |
</thead>
|
static/records.js
CHANGED
|
@@ -8,6 +8,9 @@ const statsEl = document.getElementById("stats");
|
|
| 8 |
|
| 9 |
const exportBtn = document.getElementById("exportBtn");
|
| 10 |
const exportMenu = document.getElementById("exportMenu");
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
function setStatus(msg) {
|
| 13 |
statusEl.textContent = msg || "";
|
|
@@ -47,7 +50,11 @@ exportMenu.addEventListener("click", (e) => {
|
|
| 47 |
const fmt = e.target.dataset.format;
|
| 48 |
if (!fmt) return;
|
| 49 |
setExportMenuOpen(false);
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
});
|
| 52 |
|
| 53 |
document.addEventListener("click", () => setExportMenuOpen(false));
|
|
@@ -80,6 +87,36 @@ function renderStats(stats) {
|
|
| 80 |
`;
|
| 81 |
}
|
| 82 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
function renderRows(items) {
|
| 84 |
bodyEl.innerHTML = "";
|
| 85 |
for (const item of items) {
|
|
@@ -109,6 +146,10 @@ function renderRows(items) {
|
|
| 109 |
: "—";
|
| 110 |
tr.appendChild(tdEnt);
|
| 111 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
const tdSrc = document.createElement("td");
|
| 113 |
tdSrc.textContent = item.source || "";
|
| 114 |
tr.appendChild(tdSrc);
|
|
@@ -121,8 +162,13 @@ async function load() {
|
|
| 121 |
showError("");
|
| 122 |
setStatus("Loading…");
|
| 123 |
try {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
const [recRes, statRes] = await Promise.all([
|
| 125 |
-
fetch(
|
| 126 |
fetch("/stats"),
|
| 127 |
]);
|
| 128 |
const records = await recRes.json().catch(() => null);
|
|
@@ -134,8 +180,16 @@ async function load() {
|
|
| 134 |
|
| 135 |
renderStats(stats);
|
| 136 |
buildExportMenu(stats?.export_formats || ["xml", "json", "csv"]);
|
|
|
|
|
|
|
| 137 |
|
|
|
|
|
|
|
|
|
|
| 138 |
if (!Array.isArray(records) || records.length === 0) {
|
|
|
|
|
|
|
|
|
|
| 139 |
emptyEl.hidden = false;
|
| 140 |
tableWrapper.hidden = true;
|
| 141 |
setStatus("No records yet.");
|
|
@@ -153,4 +207,7 @@ async function load() {
|
|
| 153 |
}
|
| 154 |
|
| 155 |
reloadBtn.addEventListener("click", load);
|
|
|
|
|
|
|
|
|
|
| 156 |
load();
|
|
|
|
| 8 |
|
| 9 |
const exportBtn = document.getElementById("exportBtn");
|
| 10 |
const exportMenu = document.getElementById("exportMenu");
|
| 11 |
+
const engineFilterEl = document.getElementById("engineFilter");
|
| 12 |
+
const topicFilterEl = document.getElementById("topicFilter");
|
| 13 |
+
const sentimentFilterEl = document.getElementById("sentimentFilter");
|
| 14 |
|
| 15 |
function setStatus(msg) {
|
| 16 |
statusEl.textContent = msg || "";
|
|
|
|
| 50 |
const fmt = e.target.dataset.format;
|
| 51 |
if (!fmt) return;
|
| 52 |
setExportMenuOpen(false);
|
| 53 |
+
const params = new URLSearchParams({ format: fmt });
|
| 54 |
+
if (engineFilterEl.value) params.set("engine", engineFilterEl.value);
|
| 55 |
+
if (topicFilterEl.value) params.set("topic", topicFilterEl.value);
|
| 56 |
+
if (sentimentFilterEl.value) params.set("sentiment", sentimentFilterEl.value);
|
| 57 |
+
window.location.href = `/records/export?${params.toString()}`;
|
| 58 |
});
|
| 59 |
|
| 60 |
document.addEventListener("click", () => setExportMenuOpen(false));
|
|
|
|
| 87 |
`;
|
| 88 |
}
|
| 89 |
|
| 90 |
+
// ---------------------------------------------------------------------------
|
| 91 |
+
// Topic/sentiment filter dropdowns: rebuilt from the labels /stats reports
|
| 92 |
+
// as actually in use, so they never list a topic/sentiment with 0 records.
|
| 93 |
+
// The current selection is preserved across a rebuild when still valid.
|
| 94 |
+
// ---------------------------------------------------------------------------
|
| 95 |
+
function populateFilterOptions(selectEl, keys) {
|
| 96 |
+
const current = selectEl.value;
|
| 97 |
+
selectEl.innerHTML = "";
|
| 98 |
+
const allOpt = document.createElement("option");
|
| 99 |
+
allOpt.value = "";
|
| 100 |
+
allOpt.textContent = "All";
|
| 101 |
+
selectEl.appendChild(allOpt);
|
| 102 |
+
for (const key of keys) {
|
| 103 |
+
const opt = document.createElement("option");
|
| 104 |
+
opt.value = key;
|
| 105 |
+
opt.textContent = key;
|
| 106 |
+
selectEl.appendChild(opt);
|
| 107 |
+
}
|
| 108 |
+
if (keys.includes(current)) selectEl.value = current;
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
function engineLabel(item) {
|
| 112 |
+
if (!item.provider) return "local";
|
| 113 |
+
const parts = [item.provider];
|
| 114 |
+
if (item.model) parts.push(item.model);
|
| 115 |
+
if (typeof item.latency_ms === "number") parts.push(`${item.latency_ms} ms`);
|
| 116 |
+
if (typeof item.cost_usd === "number") parts.push(`$${item.cost_usd.toFixed(4)}`);
|
| 117 |
+
return parts.join(" · ");
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
function renderRows(items) {
|
| 121 |
bodyEl.innerHTML = "";
|
| 122 |
for (const item of items) {
|
|
|
|
| 146 |
: "—";
|
| 147 |
tr.appendChild(tdEnt);
|
| 148 |
|
| 149 |
+
const tdEngine = document.createElement("td");
|
| 150 |
+
tdEngine.textContent = engineLabel(item);
|
| 151 |
+
tr.appendChild(tdEngine);
|
| 152 |
+
|
| 153 |
const tdSrc = document.createElement("td");
|
| 154 |
tdSrc.textContent = item.source || "";
|
| 155 |
tr.appendChild(tdSrc);
|
|
|
|
| 162 |
showError("");
|
| 163 |
setStatus("Loading…");
|
| 164 |
try {
|
| 165 |
+
const recParams = new URLSearchParams({ limit: "100" });
|
| 166 |
+
if (engineFilterEl.value) recParams.set("engine", engineFilterEl.value);
|
| 167 |
+
if (topicFilterEl.value) recParams.set("topic", topicFilterEl.value);
|
| 168 |
+
if (sentimentFilterEl.value) recParams.set("sentiment", sentimentFilterEl.value);
|
| 169 |
+
|
| 170 |
const [recRes, statRes] = await Promise.all([
|
| 171 |
+
fetch(`/records?${recParams.toString()}`),
|
| 172 |
fetch("/stats"),
|
| 173 |
]);
|
| 174 |
const records = await recRes.json().catch(() => null);
|
|
|
|
| 180 |
|
| 181 |
renderStats(stats);
|
| 182 |
buildExportMenu(stats?.export_formats || ["xml", "json", "csv"]);
|
| 183 |
+
populateFilterOptions(topicFilterEl, Object.keys(stats?.by_topic || {}));
|
| 184 |
+
populateFilterOptions(sentimentFilterEl, Object.keys(stats?.by_sentiment || {}));
|
| 185 |
|
| 186 |
+
const activeFilters = [engineFilterEl.value, topicFilterEl.value, sentimentFilterEl.value].filter(
|
| 187 |
+
Boolean
|
| 188 |
+
);
|
| 189 |
if (!Array.isArray(records) || records.length === 0) {
|
| 190 |
+
emptyEl.textContent = activeFilters.length
|
| 191 |
+
? `No records match the current filter (${activeFilters.join(", ")}).`
|
| 192 |
+
: "No records yet. Analyze a message or ingest a file first.";
|
| 193 |
emptyEl.hidden = false;
|
| 194 |
tableWrapper.hidden = true;
|
| 195 |
setStatus("No records yet.");
|
|
|
|
| 207 |
}
|
| 208 |
|
| 209 |
reloadBtn.addEventListener("click", load);
|
| 210 |
+
engineFilterEl.addEventListener("change", load);
|
| 211 |
+
topicFilterEl.addEventListener("change", load);
|
| 212 |
+
sentimentFilterEl.addEventListener("change", load);
|
| 213 |
load();
|
tests/test_llm_track.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Testy LLM větve (`llm_client.pipeline.LLMPipeline`).
|
| 3 |
+
|
| 4 |
+
Klient je nahrazen atrapou (`FakeClient`), takže testy běží bez API klíče
|
| 5 |
+
a bez nákladů. Tím je zároveň ověřeno, že návrh je testovatelný – jedna
|
| 6 |
+
z nefunkčních požadavků na systém.
|
| 7 |
+
|
| 8 |
+
Balíček `llm_client` už neobsahuje vlastní databázi, `evaluate` (srovnávací
|
| 9 |
+
metriky BERT vs. LLM) ani vlastní `ingest` parser - srovnání enginů bylo
|
| 10 |
+
z rozsahu vyřazeno (testování proběhne ručně a jeho výsledky budou popsány
|
| 11 |
+
přímo v diplomové práci) a LLM výsledky se ukládají stejnou cestou
|
| 12 |
+
(`db.save_record` hlavní aplikace) jako u lokální větve, viz `main.py`.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
from typing import Any, Dict, Tuple
|
| 18 |
+
|
| 19 |
+
import pytest
|
| 20 |
+
|
| 21 |
+
from llm_client.client import CallMeta, LLMClient
|
| 22 |
+
from llm_client.pipeline import LLMPipeline, _fallback_pseudonymize
|
| 23 |
+
from llm_client.schemas import AnalysisResult
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class FakeClient(LLMClient):
|
| 27 |
+
"""Deterministická atrapa poskytovatele."""
|
| 28 |
+
|
| 29 |
+
def __init__(self, payload: Dict[str, Any] | None = None):
|
| 30 |
+
self.payload = payload or {
|
| 31 |
+
"sentiment": {"label": "negative", "score": 0.91},
|
| 32 |
+
"entities": [{"text": "Jan Novák", "label": "PER", "score": 0.95}],
|
| 33 |
+
"topics": [
|
| 34 |
+
{"label": "billing and payments", "score": 0.8},
|
| 35 |
+
{"label": "complaint", "score": 0.6},
|
| 36 |
+
],
|
| 37 |
+
"pii": [
|
| 38 |
+
{
|
| 39 |
+
"text": "jan@example.com",
|
| 40 |
+
"label": "EMAIL_ADDRESS",
|
| 41 |
+
"placeholder": "<EMAIL_ADDRESS_1>",
|
| 42 |
+
}
|
| 43 |
+
],
|
| 44 |
+
"pseudonymized_text": "Dobrý den, jsem <PERSON_1>.",
|
| 45 |
+
}
|
| 46 |
+
self.calls = 0
|
| 47 |
+
|
| 48 |
+
def analyze(self, text: str) -> Tuple[Dict[str, Any], CallMeta]:
|
| 49 |
+
self.calls += 1
|
| 50 |
+
meta = CallMeta(
|
| 51 |
+
latency_ms=120,
|
| 52 |
+
tokens_in=310,
|
| 53 |
+
tokens_out=140,
|
| 54 |
+
cost_usd=0.0031,
|
| 55 |
+
model="fake-model",
|
| 56 |
+
provider="fake",
|
| 57 |
+
)
|
| 58 |
+
return self.payload, meta
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@pytest.fixture
|
| 62 |
+
def pipeline() -> LLMPipeline:
|
| 63 |
+
return LLMPipeline(provider="anthropic", mode="pre_pseudonymized", client=FakeClient())
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
# --------------------------------------------------------------------------
|
| 67 |
+
|
| 68 |
+
def test_analyze_returns_unified_contract(pipeline: LLMPipeline) -> None:
|
| 69 |
+
result = pipeline.analyze("Dobrý den, jsem Jan Novák, jan@example.com.")
|
| 70 |
+
assert isinstance(result, AnalysisResult)
|
| 71 |
+
assert result.engine == "llm"
|
| 72 |
+
assert result.sentiment.label == "negative"
|
| 73 |
+
assert result.entities[0].label == "PER"
|
| 74 |
+
assert result.top_topic == "billing and payments"
|
| 75 |
+
assert result.cost_usd > 0
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def test_labels_outside_taxonomy_are_normalised() -> None:
|
| 79 |
+
client = FakeClient(
|
| 80 |
+
{
|
| 81 |
+
"sentiment": {"label": "POSITIVE", "score": 0.7},
|
| 82 |
+
"entities": [{"text": "Brno", "label": "GPE", "score": 0.9}],
|
| 83 |
+
"topics": [{"label": "refund request", "score": 0.5}],
|
| 84 |
+
"pii": [],
|
| 85 |
+
"pseudonymized_text": "x",
|
| 86 |
+
}
|
| 87 |
+
)
|
| 88 |
+
pipe = LLMPipeline(provider="anthropic", client=client)
|
| 89 |
+
result = pipe.analyze("Brno")
|
| 90 |
+
assert result.sentiment.label == "positive" # velká písmena
|
| 91 |
+
assert result.entities[0].label == "LOC" # GPE -> LOC
|
| 92 |
+
assert result.topics[0].label == "other" # mimo číselník
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def test_raw_mode_requires_explicit_opt_in() -> None:
|
| 96 |
+
with pytest.raises(ValueError):
|
| 97 |
+
LLMPipeline(provider="anthropic", mode="raw", client=FakeClient())
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def test_pii_is_masked_before_leaving_the_system() -> None:
|
| 101 |
+
text = "Napiš mi na jan@example.com nebo na 604 123 456."
|
| 102 |
+
masked, spans = _fallback_pseudonymize(text)
|
| 103 |
+
assert "jan@example.com" not in masked
|
| 104 |
+
assert "<EMAIL_ADDRESS_1>" in masked
|
| 105 |
+
assert {s.label for s in spans} >= {"EMAIL_ADDRESS"}
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def test_client_receives_masked_text() -> None:
|
| 109 |
+
client = FakeClient()
|
| 110 |
+
captured: list[str] = []
|
| 111 |
+
original = client.analyze
|
| 112 |
+
|
| 113 |
+
def spy(text: str):
|
| 114 |
+
captured.append(text)
|
| 115 |
+
return original(text)
|
| 116 |
+
|
| 117 |
+
client.analyze = spy # type: ignore[method-assign]
|
| 118 |
+
LLMPipeline(provider="anthropic", client=client).analyze("piš na a@b.cz")
|
| 119 |
+
assert "a@b.cz" not in captured[0]
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def test_offsets_are_filled_in(pipeline: LLMPipeline) -> None:
|
| 123 |
+
result = pipeline.analyze("Zdravím, tady Jan Novák.")
|
| 124 |
+
entity = result.entities[0]
|
| 125 |
+
assert entity.start is not None and entity.end is not None
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def test_analyze_batch_reports_progress_and_preserves_order() -> None:
|
| 129 |
+
client = FakeClient()
|
| 130 |
+
pipe = LLMPipeline(provider="anthropic", client=client)
|
| 131 |
+
|
| 132 |
+
calls: list[tuple[int, int]] = []
|
| 133 |
+
texts = ["první", "druhá", "třetí"]
|
| 134 |
+
results = pipe.analyze_batch(texts, on_progress=lambda done, total: calls.append((done, total)))
|
| 135 |
+
|
| 136 |
+
assert len(results) == 3
|
| 137 |
+
assert all(isinstance(r, AnalysisResult) for r in results)
|
| 138 |
+
assert len(calls) == 3
|
| 139 |
+
assert calls[-1] == (3, 3)
|
tests/test_main_llm_integration.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Testy integrace LLM enginu do hlavní aplikace (main.py).
|
| 3 |
+
|
| 4 |
+
Srovnávací vrstva (samostatná databáze `llm_client`u, /api/llm/dashboard)
|
| 5 |
+
byla z rozsahu odstraněna - srovnání BERT vs. LLM proběhne ručně a jeho
|
| 6 |
+
výsledky budou popsány přímo v diplomové práci. Místo toho se výsledky LLM
|
| 7 |
+
enginu ukládají do STEJNÉ tabulky `records` jako výsledky lokální BERT
|
| 8 |
+
pipeline (přes `db.save_record`), aby šly zobrazit a exportovat společně.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import os
|
| 14 |
+
import tempfile
|
| 15 |
+
|
| 16 |
+
# Must happen before `db` (imported transitively via `main`) opens its
|
| 17 |
+
# connection, so these tests never touch the real project's
|
| 18 |
+
# conversation_logs.db.
|
| 19 |
+
_TEST_DB_FD, _TEST_DB_PATH = tempfile.mkstemp(suffix=".db")
|
| 20 |
+
os.close(_TEST_DB_FD)
|
| 21 |
+
os.environ["CONV_DB_PATH"] = _TEST_DB_PATH
|
| 22 |
+
|
| 23 |
+
import time
|
| 24 |
+
from unittest.mock import patch
|
| 25 |
+
|
| 26 |
+
import pytest
|
| 27 |
+
from fastapi.testclient import TestClient
|
| 28 |
+
|
| 29 |
+
import db
|
| 30 |
+
import main
|
| 31 |
+
from llm_client.client import CallMeta, LLMClient
|
| 32 |
+
from llm_client.pipeline import LLMPipeline
|
| 33 |
+
from llm_client.schemas import AnalysisResult, Entity, Sentiment, TopicScore
|
| 34 |
+
|
| 35 |
+
client = TestClient(main.app)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class FakeLLMClient(LLMClient):
|
| 39 |
+
def __init__(self, payload=None):
|
| 40 |
+
self.payload = payload or {
|
| 41 |
+
"sentiment": {"label": "positive", "score": 0.7},
|
| 42 |
+
"entities": [{"text": "Praha", "label": "LOC", "score": 0.8}],
|
| 43 |
+
"topics": [{"label": "praise and positive feedback", "score": 0.9}],
|
| 44 |
+
"pii": [],
|
| 45 |
+
"pseudonymized_text": "Diky moc!",
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
def analyze(self, text):
|
| 49 |
+
meta = CallMeta(
|
| 50 |
+
latency_ms=250,
|
| 51 |
+
tokens_in=20,
|
| 52 |
+
tokens_out=8,
|
| 53 |
+
cost_usd=0.0021,
|
| 54 |
+
model="fake-claude",
|
| 55 |
+
provider="anthropic",
|
| 56 |
+
)
|
| 57 |
+
return self.payload, meta
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _fake_llm_pipeline(*_args, **_kwargs):
|
| 61 |
+
return LLMPipeline(provider="anthropic", client=FakeLLMClient())
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_llm_result_to_response_maps_analysis_result():
|
| 65 |
+
result = AnalysisResult(
|
| 66 |
+
engine="llm",
|
| 67 |
+
provider="anthropic",
|
| 68 |
+
model="fake-claude",
|
| 69 |
+
sentiment=Sentiment(label="negative", score=0.8),
|
| 70 |
+
entities=[Entity(text="Jan", label="PER", start=0, end=3, score=0.9)],
|
| 71 |
+
topics=[TopicScore(label="complaint", score=0.6), TopicScore(label="other", score=0.1)],
|
| 72 |
+
pseudonymized_text="<PERSON_1> je nespokojeny.",
|
| 73 |
+
latency_ms=180,
|
| 74 |
+
cost_usd=0.003,
|
| 75 |
+
)
|
| 76 |
+
response = main._llm_result_to_response("Jan je nespokojeny.", result)
|
| 77 |
+
|
| 78 |
+
assert response["engine"] == "llm"
|
| 79 |
+
assert response["provider"] == "anthropic"
|
| 80 |
+
assert response["model"] == "fake-claude"
|
| 81 |
+
assert response["topic"] == "complaint"
|
| 82 |
+
assert response["sentiment"] == "negative"
|
| 83 |
+
assert response["latency_ms"] == 180
|
| 84 |
+
assert response["cost_usd"] == 0.003
|
| 85 |
+
assert response["entities"][0] == {
|
| 86 |
+
"text": "Jan",
|
| 87 |
+
"type": "PER",
|
| 88 |
+
"start": 0,
|
| 89 |
+
"end": 3,
|
| 90 |
+
"score": 0.9,
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def test_analyze_llm_engine_is_stored_in_same_records_table_as_local():
|
| 95 |
+
with patch.object(main, "LLMPipeline", side_effect=_fake_llm_pipeline):
|
| 96 |
+
resp = client.post(
|
| 97 |
+
"/analyze", json={"text": "Diky moc za pomoc!", "engine": "anthropic"}
|
| 98 |
+
)
|
| 99 |
+
assert resp.status_code == 200, resp.text
|
| 100 |
+
body = resp.json()
|
| 101 |
+
assert body["engine"] == "llm"
|
| 102 |
+
assert body["provider"] == "anthropic"
|
| 103 |
+
|
| 104 |
+
records = db.get_records(limit=5)
|
| 105 |
+
assert records[0]["engine"] == "llm"
|
| 106 |
+
assert records[0]["provider"] == "anthropic"
|
| 107 |
+
assert records[0]["model"] == "fake-claude"
|
| 108 |
+
assert records[0]["latency_ms"] == 250
|
| 109 |
+
assert records[0]["cost_usd"] == pytest.approx(0.0021)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def test_local_engine_records_keep_null_provider_and_cost():
|
| 113 |
+
with patch("main.process_message") as mock_process:
|
| 114 |
+
mock_process.return_value = {
|
| 115 |
+
"text": "ahoj",
|
| 116 |
+
"anonymized_text": "ahoj",
|
| 117 |
+
"entities": [],
|
| 118 |
+
"topic": "other",
|
| 119 |
+
"topic_score": 0.1,
|
| 120 |
+
"sentiment": "neutral",
|
| 121 |
+
"sentiment_score": 0.5,
|
| 122 |
+
}
|
| 123 |
+
resp = client.post("/analyze", json={"text": "ahoj", "engine": "local"})
|
| 124 |
+
assert resp.status_code == 200, resp.text
|
| 125 |
+
|
| 126 |
+
records = db.get_records(limit=5)
|
| 127 |
+
assert records[0]["engine"] == "local"
|
| 128 |
+
assert records[0]["provider"] is None
|
| 129 |
+
assert records[0]["cost_usd"] is None
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def test_ingest_llm_engine_stores_each_message_in_records():
|
| 133 |
+
csv_bytes = b'text\n"Skvela podpora!"\n"Objednavka nedorazila."\n'
|
| 134 |
+
with patch.object(main, "LLMPipeline", side_effect=_fake_llm_pipeline):
|
| 135 |
+
resp = client.post(
|
| 136 |
+
"/ingest",
|
| 137 |
+
files={"file": ("msgs.csv", csv_bytes, "text/csv")},
|
| 138 |
+
data={"engine": "anthropic"},
|
| 139 |
+
)
|
| 140 |
+
assert resp.status_code == 202, resp.text
|
| 141 |
+
job_id = resp.json()["job_id"]
|
| 142 |
+
|
| 143 |
+
status = None
|
| 144 |
+
for _ in range(100):
|
| 145 |
+
status = client.get(f"/ingest/status/{job_id}").json()
|
| 146 |
+
if status["status"] in ("done", "error"):
|
| 147 |
+
break
|
| 148 |
+
time.sleep(0.05)
|
| 149 |
+
|
| 150 |
+
assert status["status"] == "done", status
|
| 151 |
+
assert status["result"]["engine"] == "anthropic"
|
| 152 |
+
assert status["result"]["processed"] == 2
|
| 153 |
+
assert status["result"]["failed"] == 0
|
| 154 |
+
|
| 155 |
+
records = db.get_records(limit=10)
|
| 156 |
+
llm_records = [r for r in records if r["provider"] == "anthropic"]
|
| 157 |
+
assert len(llm_records) >= 2
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def test_analyze_llm_engine_missing_key_returns_clean_400():
|
| 161 |
+
resp = client.post("/analyze", json={"text": "hi", "engine": "google"})
|
| 162 |
+
assert resp.status_code == 400
|
| 163 |
+
assert "GEMINI_API_KEY" in resp.json()["detail"]
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def test_engines_endpoint_lists_local_and_llm_providers():
|
| 167 |
+
resp = client.get("/engines")
|
| 168 |
+
assert resp.status_code == 200
|
| 169 |
+
ids = {e["id"] for e in resp.json()["engines"]}
|
| 170 |
+
assert ids == {"local", "anthropic", "openai", "google"}
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def test_records_can_be_filtered_by_engine():
|
| 174 |
+
with patch("main.process_message") as mock_process:
|
| 175 |
+
mock_process.return_value = {
|
| 176 |
+
"text": "filter test local",
|
| 177 |
+
"anonymized_text": "filter test local",
|
| 178 |
+
"entities": [],
|
| 179 |
+
"topic": "other",
|
| 180 |
+
"topic_score": 0.1,
|
| 181 |
+
"sentiment": "neutral",
|
| 182 |
+
"sentiment_score": 0.5,
|
| 183 |
+
}
|
| 184 |
+
client.post("/analyze", json={"text": "filter test local", "engine": "local"})
|
| 185 |
+
|
| 186 |
+
with patch.object(main, "LLMPipeline", side_effect=_fake_llm_pipeline):
|
| 187 |
+
client.post(
|
| 188 |
+
"/analyze", json={"text": "filter test llm", "engine": "anthropic"}
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
local_records = client.get("/records?engine=local").json()
|
| 192 |
+
assert all(r["engine"] == "local" for r in local_records)
|
| 193 |
+
assert any(r["anonymized_text"] == "filter test local" for r in local_records)
|
| 194 |
+
|
| 195 |
+
llm_records = client.get("/records?engine=llm").json()
|
| 196 |
+
assert all(r["engine"] == "llm" for r in llm_records)
|
| 197 |
+
# FakeLLMClient always returns the same fixed payload regardless of the
|
| 198 |
+
# input text, so the stored anonymized_text is its fixed
|
| 199 |
+
# pseudonymized_text ("Diky moc!"), not the original input.
|
| 200 |
+
assert any(r["anonymized_text"] == "Diky moc!" for r in llm_records)
|
| 201 |
+
|
| 202 |
+
all_records = client.get("/records").json()
|
| 203 |
+
assert len(all_records) >= len(local_records) + len(llm_records)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def test_records_invalid_engine_filter_returns_clean_400():
|
| 207 |
+
resp = client.get("/records?engine=bogus")
|
| 208 |
+
assert resp.status_code == 400
|
| 209 |
+
assert "engine" in resp.json()["detail"].lower()
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def test_records_export_respects_engine_filter():
|
| 213 |
+
resp = client.get("/records/export?format=json&engine=llm")
|
| 214 |
+
assert resp.status_code == 200, resp.text
|
| 215 |
+
import json as _json
|
| 216 |
+
|
| 217 |
+
rows = _json.loads(resp.content)
|
| 218 |
+
assert all(r["engine"] == "llm" for r in rows)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def test_records_can_be_filtered_by_topic_and_sentiment():
|
| 222 |
+
with patch("main.process_message") as mock_process:
|
| 223 |
+
mock_process.return_value = {
|
| 224 |
+
"text": "billing complaint",
|
| 225 |
+
"anonymized_text": "billing complaint",
|
| 226 |
+
"entities": [],
|
| 227 |
+
"topic": "billing and payments",
|
| 228 |
+
"topic_score": 0.7,
|
| 229 |
+
"sentiment": "negative",
|
| 230 |
+
"sentiment_score": 0.8,
|
| 231 |
+
}
|
| 232 |
+
client.post("/analyze", json={"text": "billing complaint", "engine": "local"})
|
| 233 |
+
|
| 234 |
+
mock_process.return_value = {
|
| 235 |
+
"text": "great service",
|
| 236 |
+
"anonymized_text": "great service",
|
| 237 |
+
"entities": [],
|
| 238 |
+
"topic": "praise and positive feedback",
|
| 239 |
+
"topic_score": 0.9,
|
| 240 |
+
"sentiment": "positive",
|
| 241 |
+
"sentiment_score": 0.95,
|
| 242 |
+
}
|
| 243 |
+
client.post("/analyze", json={"text": "great service", "engine": "local"})
|
| 244 |
+
|
| 245 |
+
billing_records = client.get("/records?topic=billing and payments").json()
|
| 246 |
+
assert all(r["topic"] == "billing and payments" for r in billing_records)
|
| 247 |
+
assert any(r["anonymized_text"] == "billing complaint" for r in billing_records)
|
| 248 |
+
|
| 249 |
+
negative_records = client.get("/records?sentiment=negative").json()
|
| 250 |
+
assert all(r["sentiment"] == "negative" for r in negative_records)
|
| 251 |
+
assert any(r["anonymized_text"] == "billing complaint" for r in negative_records)
|
| 252 |
+
|
| 253 |
+
# combined filter: topic AND sentiment together
|
| 254 |
+
combined = client.get(
|
| 255 |
+
"/records?topic=billing and payments&sentiment=negative"
|
| 256 |
+
).json()
|
| 257 |
+
assert any(r["anonymized_text"] == "billing complaint" for r in combined)
|
| 258 |
+
|
| 259 |
+
# a combination with no matching record returns a clean empty list, not
|
| 260 |
+
# an error - topic/sentiment aren't a fixed enum (custom models can
|
| 261 |
+
# produce arbitrary labels), so "no matches" is a valid, non-error result
|
| 262 |
+
no_match = client.get(
|
| 263 |
+
"/records?topic=billing and payments&sentiment=positive"
|
| 264 |
+
).json()
|
| 265 |
+
assert no_match == []
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def test_records_export_respects_topic_and_sentiment_filters():
|
| 269 |
+
resp = client.get(
|
| 270 |
+
"/records/export?format=json&topic=billing and payments&sentiment=negative"
|
| 271 |
+
)
|
| 272 |
+
assert resp.status_code == 200, resp.text
|
| 273 |
+
import json as _json
|
| 274 |
+
|
| 275 |
+
rows = _json.loads(resp.content)
|
| 276 |
+
assert all(r["topic"] == "billing and payments" and r["sentiment"] == "negative" for r in rows)
|
tests/test_v8_integration.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Testy pro V8 integraci llm_client do skutečného projektu.
|
| 3 |
+
|
| 4 |
+
Na rozdíl od test_llm_track.py, tyto testy cíleně ověřují místa, kde byl
|
| 5 |
+
`llm_client` upravován, aby odpovídal *reálnému* rozhraní tohoto projektu
|
| 6 |
+
(pipeline.process_message, processors.anonymizer, processors.topics),
|
| 7 |
+
místo předpokládaného `conversation_system.*` z jiné konverzace.
|
| 8 |
+
|
| 9 |
+
Srovnávací vrstva (`BertPipelineAdapter`, `execute_run`, vlastní databáze
|
| 10 |
+
`llm_client`u) byla z rozsahu odstraněna - LLM výsledky se teď ukládají přes
|
| 11 |
+
`db.save_record` hlavní aplikace stejně jako lokální výsledky, viz
|
| 12 |
+
`test_main_llm_integration.py`.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import sys
|
| 18 |
+
import types
|
| 19 |
+
|
| 20 |
+
import pytest
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# ---------------------------------------------------------------------------
|
| 24 |
+
# Pseudonymizace proti reálnému processors.anonymizer (ne fake)
|
| 25 |
+
# ---------------------------------------------------------------------------
|
| 26 |
+
|
| 27 |
+
def test_pipeline_bridges_to_real_anonymizer_module():
|
| 28 |
+
"""
|
| 29 |
+
_load_presidio_anonymizer musí umět najít a zavolat SKUTEČNÝ
|
| 30 |
+
processors.anonymizer (anonymize_text + detect_pii), ne fiktivní
|
| 31 |
+
conversation_system.processors.anonymizer.pseudonymize.
|
| 32 |
+
"""
|
| 33 |
+
from llm_client.pipeline import _load_presidio_anonymizer
|
| 34 |
+
|
| 35 |
+
pseudonymize = _load_presidio_anonymizer()
|
| 36 |
+
assert pseudonymize is not None, (
|
| 37 |
+
"processors.anonymizer by měl být dostupný (je součástí stejného projektu) "
|
| 38 |
+
"- pokud tohle selže, bridge stále odkazuje na starou cestu."
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
masked, spans = pseudonymize("Contact John Smith at john@example.com")
|
| 42 |
+
assert "john@example.com" not in masked
|
| 43 |
+
|
| 44 |
+
from processors import anonymizer as real_anonymizer
|
| 45 |
+
|
| 46 |
+
if real_anonymizer.backend_name() == "presidio":
|
| 47 |
+
# detect_pii() only returns structured spans when Presidio is actually
|
| 48 |
+
# installed; in regex-fallback mode (e.g. this sandboxed test run,
|
| 49 |
+
# where presidio-analyzer isn't installed) anonymize_text() still
|
| 50 |
+
# masks the email via regex, but detect_pii() legitimately returns [].
|
| 51 |
+
assert any(getattr(s, "entity_type", None) == "EMAIL_ADDRESS" for s in spans)
|
| 52 |
+
else:
|
| 53 |
+
assert spans == []
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_llm_pipeline_uses_real_anonymizer_end_to_end():
|
| 57 |
+
from llm_client.pipeline import LLMPipeline
|
| 58 |
+
from llm_client.client import CallMeta, LLMClient
|
| 59 |
+
|
| 60 |
+
class FakeClient(LLMClient):
|
| 61 |
+
def __init__(self):
|
| 62 |
+
self.seen_text = None
|
| 63 |
+
|
| 64 |
+
def analyze(self, text):
|
| 65 |
+
self.seen_text = text
|
| 66 |
+
return (
|
| 67 |
+
{
|
| 68 |
+
"sentiment": {"label": "negative", "score": 0.8},
|
| 69 |
+
"entities": [],
|
| 70 |
+
"topics": [{"label": "complaint", "score": 0.5}],
|
| 71 |
+
"pii": [],
|
| 72 |
+
"pseudonymized_text": text,
|
| 73 |
+
},
|
| 74 |
+
CallMeta(latency_ms=10, tokens_in=5, tokens_out=5, cost_usd=0.0, model="fake", provider="fake"),
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
client = FakeClient()
|
| 78 |
+
pipe = LLMPipeline(provider="anthropic", mode="pre_pseudonymized", client=client)
|
| 79 |
+
pipe.analyze("Email me at real.person@example.com")
|
| 80 |
+
assert "real.person@example.com" not in client.seen_text
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
# ---------------------------------------------------------------------------
|
| 84 |
+
# Sjednocená taxonomie témat
|
| 85 |
+
# ---------------------------------------------------------------------------
|
| 86 |
+
|
| 87 |
+
def test_topic_taxonomy_matches_real_zero_shot_labels():
|
| 88 |
+
from llm_client.config import TOPIC_LABELS
|
| 89 |
+
from processors.topics import DEFAULT_LABELS
|
| 90 |
+
|
| 91 |
+
assert TOPIC_LABELS == DEFAULT_LABELS
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# ---------------------------------------------------------------------------
|
| 95 |
+
# Gemini client (atrapa SDK - žádný reálný klíč/síťové volání)
|
| 96 |
+
# ---------------------------------------------------------------------------
|
| 97 |
+
|
| 98 |
+
class _FakeGeminiResponse:
|
| 99 |
+
def __init__(self, text, prompt_tokens=100, output_tokens=50):
|
| 100 |
+
self.text = text
|
| 101 |
+
self.usage_metadata = types.SimpleNamespace(
|
| 102 |
+
prompt_token_count=prompt_tokens, candidates_token_count=output_tokens
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class _FakeGenerativeModel:
|
| 107 |
+
last_instance = None
|
| 108 |
+
|
| 109 |
+
def __init__(self, model_name, system_instruction=None):
|
| 110 |
+
self.model_name = model_name
|
| 111 |
+
self.system_instruction = system_instruction
|
| 112 |
+
self.last_call = None
|
| 113 |
+
_FakeGenerativeModel.last_instance = self
|
| 114 |
+
|
| 115 |
+
def generate_content(self, prompt, generation_config=None):
|
| 116 |
+
self.last_call = {"prompt": prompt, "generation_config": generation_config}
|
| 117 |
+
import json
|
| 118 |
+
|
| 119 |
+
payload = {
|
| 120 |
+
"sentiment": {"label": "positive", "score": 0.77},
|
| 121 |
+
"entities": [],
|
| 122 |
+
"topics": [{"label": "praise and positive feedback", "score": 0.9}],
|
| 123 |
+
"pii": [],
|
| 124 |
+
"pseudonymized_text": prompt,
|
| 125 |
+
}
|
| 126 |
+
return _FakeGeminiResponse(json.dumps(payload))
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _install_fake_genai(monkeypatch):
|
| 130 |
+
fake_genai = types.SimpleNamespace(
|
| 131 |
+
configure=lambda api_key=None: None,
|
| 132 |
+
GenerativeModel=_FakeGenerativeModel,
|
| 133 |
+
GenerationConfig=lambda **kw: kw,
|
| 134 |
+
)
|
| 135 |
+
fake_google = types.SimpleNamespace(generativeai=fake_genai)
|
| 136 |
+
monkeypatch.setitem(sys.modules, "google", fake_google)
|
| 137 |
+
monkeypatch.setitem(sys.modules, "google.generativeai", fake_genai)
|
| 138 |
+
return fake_genai
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def test_gemini_client_builds_request_and_parses_response(monkeypatch):
|
| 142 |
+
monkeypatch.setenv("GEMINI_API_KEY", "fake-key-for-tests")
|
| 143 |
+
_install_fake_genai(monkeypatch)
|
| 144 |
+
|
| 145 |
+
from llm_client.client import GeminiClient
|
| 146 |
+
from llm_client.config import PROVIDERS
|
| 147 |
+
|
| 148 |
+
client = GeminiClient(PROVIDERS["google"])
|
| 149 |
+
payload, meta = client.analyze("Great support, thank you!")
|
| 150 |
+
|
| 151 |
+
assert payload["sentiment"]["label"] == "positive"
|
| 152 |
+
assert meta.provider == "google"
|
| 153 |
+
assert meta.tokens_in == 100
|
| 154 |
+
assert meta.tokens_out == 50
|
| 155 |
+
assert meta.cost_usd > 0
|
| 156 |
+
|
| 157 |
+
call = _FakeGenerativeModel.last_instance.last_call
|
| 158 |
+
assert "Great support" in call["prompt"]
|
| 159 |
+
assert call["generation_config"]["response_mime_type"] == "application/json"
|
| 160 |
+
assert "response_schema" in call["generation_config"]
|
| 161 |
+
|
| 162 |
+
schema = call["generation_config"]["response_schema"]
|
| 163 |
+
|
| 164 |
+
def _assert_no_minmax(node):
|
| 165 |
+
if isinstance(node, dict):
|
| 166 |
+
assert "minimum" not in node, "Gemini's Schema proto rejects 'minimum'"
|
| 167 |
+
assert "maximum" not in node, "Gemini's Schema proto rejects 'maximum'"
|
| 168 |
+
for v in node.values():
|
| 169 |
+
_assert_no_minmax(v)
|
| 170 |
+
elif isinstance(node, list):
|
| 171 |
+
for item in node:
|
| 172 |
+
_assert_no_minmax(item)
|
| 173 |
+
|
| 174 |
+
_assert_no_minmax(schema)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def test_gemini_schema_strips_minmax_but_other_clients_keep_it():
|
| 178 |
+
from llm_client import prompts
|
| 179 |
+
|
| 180 |
+
gemini = prompts.gemini_schema()
|
| 181 |
+
anthropic_tool = prompts.anthropic_tool()
|
| 182 |
+
|
| 183 |
+
assert "minimum" not in gemini["properties"]["sentiment"]["properties"]["score"]
|
| 184 |
+
assert (
|
| 185 |
+
anthropic_tool["input_schema"]["properties"]["sentiment"]["properties"]["score"]["minimum"]
|
| 186 |
+
== 0
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def test_gemini_missing_api_key_raises_clean_error(monkeypatch):
|
| 191 |
+
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
|
| 192 |
+
_install_fake_genai(monkeypatch)
|
| 193 |
+
|
| 194 |
+
from llm_client.client import LLMError, get_client
|
| 195 |
+
|
| 196 |
+
with pytest.raises(LLMError):
|
| 197 |
+
get_client("google")
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def test_provider_registry_includes_all_three():
|
| 201 |
+
from llm_client.client import _REGISTRY
|
| 202 |
+
|
| 203 |
+
assert set(_REGISTRY) == {"anthropic", "openai", "google"}
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def test_google_gemini_is_the_default_llm_provider(monkeypatch):
|
| 207 |
+
"""
|
| 208 |
+
Gemini has a usable free tier, unlike Anthropic/OpenAI - it's the
|
| 209 |
+
fallback provider when a caller doesn't specify an ``engine``/``provider``
|
| 210 |
+
explicitly (e.g. a direct ``LLMPipeline()`` call with no arguments).
|
| 211 |
+
``Settings.default_provider`` reads ``LLM_PROVIDER`` fresh on every
|
| 212 |
+
``Settings()`` construction (it's a ``default_factory``, not a value
|
| 213 |
+
fixed at import time), so no module reload is needed here.
|
| 214 |
+
"""
|
| 215 |
+
from llm_client.config import Settings
|
| 216 |
+
|
| 217 |
+
monkeypatch.delenv("LLM_PROVIDER", raising=False)
|
| 218 |
+
assert Settings().default_provider == "google"
|