File size: 9,653 Bytes
f390b04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84cd1aa
f390b04
84cd1aa
f390b04
 
 
 
 
 
 
2e3f5aa
f390b04
 
 
84cd1aa
 
 
 
 
 
 
 
 
f390b04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e3f5aa
 
84cd1aa
 
2e3f5aa
 
 
 
 
 
 
 
 
 
 
 
 
 
84cd1aa
 
 
 
 
 
 
 
 
2e3f5aa
84cd1aa
2e3f5aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84cd1aa
2e3f5aa
 
 
 
 
 
 
 
84cd1aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
"""
Database layer (SQLite).

Stores the structured output of the pipeline in a pseudonymized form. The
original text is never stored in readable form: only a SHA-256 hash (for
deduplication) and the anonymized text are persisted, together with the
extracted entities, topic and sentiment.

SQLite was chosen for the prototype (serverless, zero-config, portable). The
layer is intentionally small so it can be swapped for PostgreSQL in a
production deployment without changing the rest of the application.
"""

from __future__ import annotations

import csv
import hashlib
import io
import json
import os
import sqlite3
import threading
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from xml.etree import ElementTree as ET

from processors import anonymizer

# Export formats supported by export_records(), each mapped to its HTTP
# media type. Adding a new format only requires a new "_export_<fmt>"
# function plus an entry here.
EXPORT_FORMATS = {
    "xml": "application/xml",
    "json": "application/json",
    "csv": "text/csv",
}

# ---------------------------------------------------------------------------
# Database location: project folder on Windows, /tmp on Linux (HF Spaces).
# ---------------------------------------------------------------------------
if os.name == "nt":
    DB_PATH = os.getenv(
        "CONV_DB_PATH",
        str((Path(__file__).resolve().parent / "conversation_logs.db")),
    )
else:
    DB_PATH = os.getenv("CONV_DB_PATH", "/tmp/conversation_logs.db")

_db_lock = threading.Lock()


def _get_connection() -> sqlite3.Connection:
    conn = sqlite3.connect(DB_PATH, check_same_thread=False)
    conn.execute(
        """
        CREATE TABLE IF NOT EXISTS records (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            created_at TEXT NOT NULL,
            original_hash TEXT NOT NULL,
            anonymized_text TEXT NOT NULL,
            entities TEXT,            -- JSON array
            topic TEXT,
            topic_score REAL,
            sentiment TEXT,
            sentiment_score REAL,
            conversation_id TEXT,
            source TEXT               -- 'single' or 'ingest'
        )
        """
    )
    conn.commit()
    return conn


_db_conn = _get_connection()


def _utcnow() -> str:
    return datetime.now(timezone.utc).isoformat(timespec="seconds")


def save_record(result: dict[str, Any], source: str = "single") -> None:
    """
    Persist one pipeline result. The original text is hashed (not stored);
    the anonymized text is stored. If the result does not already contain an
    anonymized text, it is anonymized here as a safeguard.
    """
    original_text = result.get("text", "") or ""
    anonymized = result.get("anonymized_text") or anonymizer.anonymize_text(original_text)
    original_hash = hashlib.sha256(original_text.encode("utf-8")).hexdigest()

    entities_json = json.dumps(result.get("entities", []), ensure_ascii=False)

    with _db_lock:
        _db_conn.execute(
            """
            INSERT INTO records (
                created_at, original_hash, anonymized_text, entities,
                topic, topic_score, sentiment, sentiment_score,
                conversation_id, source
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            """,
            (
                _utcnow(),
                original_hash,
                anonymized,
                entities_json,
                result.get("topic"),
                result.get("topic_score"),
                result.get("sentiment"),
                result.get("sentiment_score"),
                result.get("conversation_id"),
                source,
            ),
        )
        _db_conn.commit()


def get_records(limit: int = 100) -> list[dict[str, Any]]:
    """Return the most recent records (anonymized only)."""
    with _db_lock:
        cur = _db_conn.execute(
            """
            SELECT id, created_at, anonymized_text, entities,
                   topic, topic_score, sentiment, sentiment_score,
                   conversation_id, source
            FROM records
            ORDER BY id DESC
            LIMIT ?
            """,
            (limit,),
        )
        rows = cur.fetchall()

    records = []
    for r in rows:
        try:
            entities = json.loads(r[3]) if r[3] else []
        except Exception:
            entities = []
        records.append(
            {
                "id": r[0],
                "created_at": r[1],
                "anonymized_text": r[2],
                "entities": entities,
                "topic": r[4],
                "topic_score": r[5],
                "sentiment": r[6],
                "sentiment_score": r[7],
                "conversation_id": r[8],
                "source": r[9],
            }
        )
    return records


def stats() -> dict[str, Any]:
    """Aggregate statistics for the dashboard (counts by sentiment / topic)."""
    with _db_lock:
        total = _db_conn.execute("SELECT COUNT(*) FROM records").fetchone()[0]
        by_sentiment = _db_conn.execute(
            "SELECT sentiment, COUNT(*) FROM records GROUP BY sentiment"
        ).fetchall()
        by_topic = _db_conn.execute(
            "SELECT topic, COUNT(*) FROM records GROUP BY topic ORDER BY COUNT(*) DESC LIMIT 10"
        ).fetchall()

    return {
        "total": total,
        "by_sentiment": {(s or "unknown"): c for s, c in by_sentiment},
        "by_topic": {(t or "unknown"): c for t, c in by_topic},
    }


def _fetch_export_rows(limit: int | None) -> list[tuple[Any, ...]]:
    """Raw rows (most recent first) shared by every export format."""
    query = """
        SELECT id, created_at, anonymized_text, entities,
               topic, topic_score, sentiment, sentiment_score,
               conversation_id, source
        FROM records
        ORDER BY id DESC
    """
    if limit is not None:
        query += " LIMIT ?"
        params: tuple[Any, ...] = (limit,)
    else:
        params = ()

    with _db_lock:
        return _db_conn.execute(query, params).fetchall()


def _row_entities(row: tuple[Any, ...]) -> list[dict[str, Any]]:
    try:
        return json.loads(row[3]) if row[3] else []
    except Exception:
        return []


def _export_xml(rows: list[tuple[Any, ...]]) -> bytes:
    root = ET.Element("records")
    for r in rows:
        record_el = ET.SubElement(root, "record", id=str(r[0]))
        ET.SubElement(record_el, "created_at").text = r[1]
        ET.SubElement(record_el, "anonymized_text").text = r[2]
        ET.SubElement(record_el, "topic").text = r[4]
        ET.SubElement(record_el, "topic_score").text = (
            str(r[5]) if r[5] is not None else None
        )
        ET.SubElement(record_el, "sentiment").text = r[6]
        ET.SubElement(record_el, "sentiment_score").text = (
            str(r[7]) if r[7] is not None else None
        )
        ET.SubElement(record_el, "conversation_id").text = r[8]
        ET.SubElement(record_el, "source").text = r[9]

        entities_el = ET.SubElement(record_el, "entities")
        for ent in _row_entities(r):
            ET.SubElement(
                entities_el,
                "entity",
                type=str(ent.get("type", "")),
                score=str(ent.get("score", "")),
            ).text = ent.get("text", "")

    return ET.tostring(root, encoding="utf-8", xml_declaration=True)


def _export_json(rows: list[tuple[Any, ...]]) -> bytes:
    records = [
        {
            "id": r[0],
            "created_at": r[1],
            "anonymized_text": r[2],
            "entities": _row_entities(r),
            "topic": r[4],
            "topic_score": r[5],
            "sentiment": r[6],
            "sentiment_score": r[7],
            "conversation_id": r[8],
            "source": r[9],
        }
        for r in rows
    ]
    return json.dumps(records, ensure_ascii=False, indent=2).encode("utf-8")


def _export_csv(rows: list[tuple[Any, ...]]) -> bytes:
    # CSV is flat, so entities (a nested list) are serialized into a single
    # "TYPE:text" cell per entity, semicolon-separated.
    buffer = io.StringIO()
    writer = csv.writer(buffer)
    writer.writerow(
        [
            "id",
            "created_at",
            "anonymized_text",
            "topic",
            "topic_score",
            "sentiment",
            "sentiment_score",
            "conversation_id",
            "source",
            "entities",
        ]
    )
    for r in rows:
        entities_cell = "; ".join(
            f"{ent.get('type', '')}:{ent.get('text', '')}" for ent in _row_entities(r)
        )
        writer.writerow([r[0], r[1], r[2], r[4], r[5], r[6], r[7], r[8], r[9], entities_cell])

    # utf-8-sig (BOM) so Excel opens the file with correct encoding.
    return buffer.getvalue().encode("utf-8-sig")


def export_records(fmt: str, limit: int | None = None) -> tuple[bytes, str]:
    """
    Export stored (anonymized) records in the given format.

    Returns ``(content_bytes, media_type)``. Raises ``ValueError`` for an
    unsupported ``fmt`` so the API layer can turn it into a clean 400
    response. ``limit`` caps the number of most recent records exported;
    ``None`` exports everything.
    """
    fmt = (fmt or "xml").strip().lower()
    if fmt not in EXPORT_FORMATS:
        supported = ", ".join(sorted(EXPORT_FORMATS))
        raise ValueError(f"Unsupported export format '{fmt}'. Supported: {supported}.")

    rows = _fetch_export_rows(limit)
    exporter = {"xml": _export_xml, "json": _export_json, "csv": _export_csv}[fmt]
    return exporter(rows), EXPORT_FORMATS[fmt]