Download src/logging_layer/analytics_logger.py from danishk84/NovaGuide: direct link, hf CLI and curl.
- Browser
- Download file 20.1 kB
-
https://huggingface.co/spaces/danishk84/NovaGuide/resolve/main/src/logging_layer/analytics_logger.py
- Command line
-
hf download hf://spaces/danishk84/NovaGuide/src/logging_layer/analytics_logger.py
-
curl -L -o analytics_logger.py https://huggingface.co/spaces/danishk84/NovaGuide/resolve/main/src/logging_layer/analytics_logger.py
20.1 kB
| """Privacy-aware Neon logging with local CSV fallback.""" | |
| from __future__ import annotations | |
| import csv | |
| import json | |
| import re | |
| from pathlib import Path | |
| from typing import Any | |
| from src.config import Settings, get_settings | |
| from src.logging_layer.neon_client import NeonClient | |
| from src.utils.ids import ( | |
| generate_event_id, | |
| generate_interaction_id, | |
| generate_session_id, | |
| ) | |
| from src.utils.sanitization import sanitize_text | |
| from src.utils.timing import current_utc_iso | |
| INTERACTION_FIELDS = ( | |
| "interaction_id", | |
| "session_id", | |
| "timestamp", | |
| "data_source", | |
| "test_run_id", | |
| "configuration_version", | |
| "input_modality", | |
| "sanitized_query", | |
| "transcribed_text_sanitized", | |
| "image_category", | |
| "predicted_intent", | |
| "intent_confidence", | |
| "extracted_entities_json", | |
| "route", | |
| "matched_record_id", | |
| "matched_record_name", | |
| "retrieval_score", | |
| "final_confidence", | |
| "fallback_triggered", | |
| "response_time_ms", | |
| "time_to_first_response_ms", | |
| "intent_latency_ms", | |
| "retrieval_latency_ms", | |
| "vision_latency_ms", | |
| "speech_latency_ms", | |
| "task_completed", | |
| "model_used", | |
| "sources_used_json", | |
| "safety_notes_json", | |
| "expected_intent", | |
| "intent_correct", | |
| "fallback_reason", | |
| ) | |
| FEEDBACK_FIELDS = ( | |
| "feedback_id", | |
| "interaction_id", | |
| "session_id", | |
| "rating", | |
| "comment_sanitized", | |
| "frustration_flag", | |
| "created_at", | |
| ) | |
| API_FIELDS = ( | |
| "api_call_id", | |
| "interaction_id", | |
| "provider", | |
| "api_type", | |
| "success", | |
| "status_code", | |
| "duration_ms", | |
| "error_sanitized", | |
| "created_at", | |
| ) | |
| VALID_FEEDBACK_RATINGS = {"helpful", "not_helpful", "neutral"} | |
| FRUSTRATION_PATTERN = re.compile( | |
| r"\b(wrong|not helpful|confused|useless|frustrated|again|still not)\b", | |
| re.IGNORECASE, | |
| ) | |
| TEST_RUN_INSERT = """INSERT INTO test_runs ( | |
| run_id, test_type, tool, configuration_version, started_at | |
| ) VALUES ( | |
| :run_id, :test_type, :tool, :configuration_version, :started_at | |
| ) ON CONFLICT (run_id) DO NOTHING""" | |
| SESSION_INSERT = """INSERT INTO chat_sessions ( | |
| session_id, started_at, user_type, channel | |
| ) VALUES ( | |
| :session_id, :started_at, :user_type, :channel | |
| ) ON CONFLICT (session_id) DO NOTHING""" | |
| SESSION_UPDATE = """UPDATE chat_sessions | |
| SET ended_at = :ended_at, completed = :completed | |
| WHERE session_id = :session_id""" | |
| INTERACTION_INSERT = """INSERT INTO chat_interactions ( | |
| interaction_id, session_id, timestamp, data_source, test_run_id, | |
| configuration_version, input_modality, sanitized_query, | |
| transcribed_text_sanitized, image_category, predicted_intent, | |
| intent_confidence, extracted_entities_json, route, matched_record_id, | |
| matched_record_name, retrieval_score, final_confidence, | |
| fallback_triggered, response_time_ms, time_to_first_response_ms, | |
| intent_latency_ms, retrieval_latency_ms, vision_latency_ms, | |
| speech_latency_ms, task_completed, model_used, sources_used_json, | |
| safety_notes_json | |
| ) VALUES ( | |
| :interaction_id, :session_id, :timestamp, :data_source, | |
| NULLIF(:test_run_id, ''), :configuration_version, :input_modality, | |
| :sanitized_query, :transcribed_text_sanitized, :image_category, | |
| :predicted_intent, :intent_confidence, | |
| CAST(:extracted_entities_json AS JSONB), :route, :matched_record_id, | |
| :matched_record_name, :retrieval_score, :final_confidence, | |
| :fallback_triggered, :response_time_ms, :time_to_first_response_ms, | |
| :intent_latency_ms, :retrieval_latency_ms, :vision_latency_ms, | |
| :speech_latency_ms, :task_completed, :model_used, | |
| CAST(:sources_used_json AS JSONB), CAST(:safety_notes_json AS JSONB) | |
| )""" | |
| INTENT_INSERT = """INSERT INTO intent_predictions ( | |
| prediction_id, interaction_id, expected_intent, predicted_intent, | |
| confidence, correct, model_source, all_scores_json | |
| ) VALUES ( | |
| :id, :interaction_id, :expected, :predicted, :confidence, :correct, | |
| :source, CAST(:scores AS JSONB) | |
| )""" | |
| RETRIEVAL_INSERT = """INSERT INTO retrieval_results ( | |
| retrieval_id, interaction_id, retrieval_type, top_k_results_json, | |
| selected_record_id, selected_record_name, similarity_score, | |
| expected_record_id, retrieval_correct | |
| ) VALUES ( | |
| :id, :interaction_id, :type, CAST(:results AS JSONB), :record_id, | |
| :record_name, :score, :expected_record_id, :retrieval_correct | |
| )""" | |
| VISION_INSERT = """INSERT INTO vision_events ( | |
| vision_event_id, interaction_id, ocr_used, ocr_text_sanitized, | |
| ocr_confidence, clip_used, clip_category, clip_confidence, | |
| qwen_invoked, qwen_success, qwen_reason, processing_time_ms | |
| ) VALUES ( | |
| :id, :interaction_id, :ocr_used, :ocr_text, :ocr_confidence, | |
| :clip_used, :clip_category, :clip_confidence, :qwen_invoked, | |
| :qwen_success, :qwen_reason, :processing_time_ms | |
| )""" | |
| FALLBACK_INSERT = """INSERT INTO fallback_events ( | |
| fallback_id, interaction_id, fallback_reason, route, intent, | |
| confidence, recommended_action | |
| ) VALUES ( | |
| :id, :interaction_id, :reason, :route, :intent, :confidence, :action | |
| )""" | |
| FEEDBACK_INSERT = """INSERT INTO feedback_events ( | |
| feedback_id, interaction_id, session_id, rating, comment_sanitized, | |
| frustration_flag, created_at | |
| ) VALUES ( | |
| :feedback_id, :interaction_id, :session_id, :rating, | |
| :comment_sanitized, :frustration_flag, :created_at | |
| )""" | |
| API_CALL_INSERT = """INSERT INTO api_call_logs ( | |
| api_call_id, interaction_id, provider, api_type, success, status_code, | |
| duration_ms, error_sanitized, created_at | |
| ) VALUES ( | |
| :api_call_id, NULLIF(:interaction_id, ''), :provider, :api_type, | |
| :success, :status_code, :duration_ms, :error_sanitized, :created_at | |
| )""" | |
| def detect_frustration(rating: str, comment: str | None = None) -> bool: | |
| """Return whether explicit feedback contains a controlled friction signal.""" | |
| clean_comment = sanitize_text(comment) | |
| return rating == "not_helpful" or bool(FRUSTRATION_PATTERN.search(clean_comment)) | |
| class AnalyticsLogger: | |
| def __init__( | |
| self, settings: Settings | None = None, neon_client: NeonClient | None = None | |
| ) -> None: | |
| self.settings = settings or get_settings() | |
| self.neon = neon_client or NeonClient(self.settings) | |
| self.sessions = set() | |
| def _append(path: str, fields: tuple[str, ...], row: dict[str, Any]) -> None: | |
| target = Path(path) | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| exists = target.is_file() and target.stat().st_size > 0 | |
| with target.open("a", encoding="utf-8", newline="") as handle: | |
| writer = csv.DictWriter(handle, fieldnames=fields, extrasaction="ignore") | |
| if not exists: | |
| writer.writeheader() | |
| writer.writerow({field: row.get(field, "") for field in fields}) | |
| def _store( | |
| self, | |
| query: str, | |
| params: dict[str, Any], | |
| path: str | None = None, | |
| fields: tuple[str, ...] | None = None, | |
| ) -> str: | |
| if self.neon.is_configured() and self.neon.execute(query, params): | |
| return "neon" | |
| if self.settings.fallback_to_csv_logs and path and fields: | |
| self._append(path, fields, params) | |
| return "csv" | |
| return "memory" | |
| def ensure_test_run( | |
| self, run_id: str | None, data_source: str, tool: str | None = None | |
| ) -> bool: | |
| """Create the referenced test run before storing interaction events.""" | |
| run_id = (run_id or "").strip() | |
| if not run_id or not self.neon.is_configured(): | |
| return True | |
| tool_name = tool or ( | |
| { | |
| "locust": "locust", | |
| "hypothesis": "hypothesis", | |
| "structured_test": "gradio", | |
| }.get(data_source, "novaguide") | |
| ) | |
| return self.neon.execute( | |
| TEST_RUN_INSERT, | |
| { | |
| "run_id": run_id, | |
| "test_type": data_source, | |
| "tool": tool_name, | |
| "configuration_version": self.settings.configuration_version, | |
| "started_at": current_utc_iso(), | |
| }, | |
| ) | |
| def start_session( | |
| self, | |
| session_id: str | None = None, | |
| user_type: str = "anonymous", | |
| channel: str = "gradio", | |
| ) -> dict[str, Any]: | |
| sid = session_id or generate_session_id() | |
| self.sessions.add(sid) | |
| stored = "csv" if self.settings.fallback_to_csv_logs else "memory" | |
| if self.neon.is_configured(): | |
| stored = self._store( | |
| SESSION_INSERT, | |
| { | |
| "session_id": sid, | |
| "started_at": current_utc_iso(), | |
| "user_type": user_type, | |
| "channel": channel, | |
| }, | |
| ) | |
| return {"success": True, "session_id": sid, "stored_in": stored, "error": None} | |
| def end_session(self, session_id: str, completed: bool = True) -> bool: | |
| self.sessions.discard(session_id) | |
| return ( | |
| self.neon.execute( | |
| SESSION_UPDATE, | |
| { | |
| "ended_at": current_utc_iso(), | |
| "completed": completed, | |
| "session_id": session_id, | |
| }, | |
| ) | |
| if self.neon.is_configured() | |
| else True | |
| ) | |
| def _build_interaction_row( | |
| self, | |
| interaction_id: str, | |
| session_id: str, | |
| response: dict[str, Any], | |
| user: dict[str, Any], | |
| expected_intent: str | None, | |
| task_completed: bool | None, | |
| ) -> dict[str, Any]: | |
| """Build the normalised analytics record for one chatbot interaction.""" | |
| intent = response.get("intent", "") | |
| debug = response.get("debug", {}) or {} | |
| image_result = user.get("image_result", {}) or {} | |
| speech_result = user.get("speech_result", {}) or {} | |
| qwen_result = image_result.get("qwen") or {} | |
| return { | |
| "interaction_id": interaction_id, | |
| "session_id": session_id, | |
| "timestamp": current_utc_iso(), | |
| "data_source": user.get("data_source") | |
| or self.settings.analytics_data_source, | |
| "test_run_id": user.get("test_run_id", ""), | |
| "configuration_version": user.get("configuration_version") | |
| or self.settings.configuration_version, | |
| "input_modality": user.get("modality") or response.get("modality", "text"), | |
| "sanitized_query": sanitize_text(user.get("text")), | |
| "transcribed_text_sanitized": sanitize_text(user.get("transcribed_text")), | |
| "image_category": sanitize_text(user.get("image_category")), | |
| "predicted_intent": intent, | |
| "intent_confidence": float(response.get("intent_confidence", 0)), | |
| "extracted_entities_json": json.dumps(response.get("entities", {})), | |
| "route": response.get("route", ""), | |
| "matched_record_id": response.get("matched_record_id") or "", | |
| "matched_record_name": response.get("matched_record_name") or "", | |
| "retrieval_score": float(response.get("retrieval_score", 0)), | |
| "final_confidence": float(response.get("final_confidence", 0)), | |
| "fallback_triggered": bool(response.get("fallback_triggered")), | |
| "response_time_ms": int(response.get("response_time_ms", 0)), | |
| "time_to_first_response_ms": int( | |
| response.get( | |
| "time_to_first_response_ms", response.get("response_time_ms", 0) | |
| ) | |
| ), | |
| "intent_latency_ms": int(debug.get("intent_latency_ms", 0) or 0), | |
| "retrieval_latency_ms": int(debug.get("retrieval_latency_ms", 0) or 0), | |
| "vision_latency_ms": int(image_result.get("processing_time_ms", 0) or 0), | |
| "speech_latency_ms": int(speech_result.get("processing_time_ms", 0) or 0), | |
| "task_completed": None if task_completed is None else bool(task_completed), | |
| "model_used": debug.get("llm_model") | |
| or ("qwen_vl" if qwen_result.get("success") else "template"), | |
| "sources_used_json": json.dumps(response.get("sources_used", {})), | |
| "safety_notes_json": json.dumps(response.get("safety_notes", [])), | |
| "expected_intent": expected_intent or "", | |
| "intent_correct": ( | |
| None if expected_intent is None else expected_intent == intent | |
| ), | |
| "fallback_reason": ( | |
| debug.get("routing_reason", "") | |
| if response.get("fallback_triggered") | |
| else "" | |
| ), | |
| } | |
| def log_interaction( | |
| self, | |
| session_id: str, | |
| response: dict[str, Any], | |
| user_input: dict[str, Any] | None = None, | |
| expected_intent: str | None = None, | |
| task_completed: bool | None = None, | |
| ) -> dict[str, Any]: | |
| user = user_input or {} | |
| iid = generate_interaction_id() | |
| intent = response.get("intent", "") | |
| debug = response.get("debug", {}) or {} | |
| image_result = user.get("image_result", {}) or {} | |
| row = self._build_interaction_row( | |
| iid, | |
| session_id, | |
| response, | |
| user, | |
| expected_intent, | |
| task_completed, | |
| ) | |
| self.ensure_test_run(row["test_run_id"], row["data_source"]) | |
| query = INTERACTION_INSERT | |
| stored = self._store( | |
| query, row, self.settings.local_interactions_log, INTERACTION_FIELDS | |
| ) | |
| if stored == "neon": | |
| self.neon.execute( | |
| INTENT_INSERT, | |
| { | |
| "id": generate_event_id("pred"), | |
| "interaction_id": iid, | |
| "expected": expected_intent, | |
| "predicted": intent, | |
| "confidence": row["intent_confidence"], | |
| "correct": ( | |
| None if expected_intent is None else expected_intent == intent | |
| ), | |
| "source": debug.get("intent_source", ""), | |
| "scores": "{}", | |
| }, | |
| ) | |
| if row["matched_record_id"]: | |
| self.neon.execute( | |
| RETRIEVAL_INSERT, | |
| { | |
| "id": generate_event_id("ret"), | |
| "interaction_id": iid, | |
| "type": row["route"], | |
| "results": json.dumps(debug.get("retrieval_results", [])), | |
| "record_id": row["matched_record_id"], | |
| "record_name": row["matched_record_name"], | |
| "score": row["retrieval_score"], | |
| "expected_record_id": user.get("expected_record_id") or None, | |
| "retrieval_correct": ( | |
| None | |
| if not user.get("expected_record_id") | |
| else user.get("expected_record_id") | |
| == row["matched_record_id"] | |
| ), | |
| }, | |
| ) | |
| if image_result: | |
| self.neon.execute( | |
| VISION_INSERT, | |
| { | |
| "id": generate_event_id("vision"), | |
| "interaction_id": iid, | |
| "ocr_used": bool( | |
| (image_result.get("ocr") or {}).get("success") | |
| ), | |
| "ocr_text": sanitize_text( | |
| (image_result.get("ocr") or {}).get("text") | |
| ), | |
| "ocr_confidence": float( | |
| (image_result.get("ocr") or {}).get("confidence", 0) or 0 | |
| ), | |
| "clip_used": bool(image_result.get("success")), | |
| "clip_category": sanitize_text( | |
| image_result.get("predicted_category") | |
| ), | |
| "clip_confidence": float( | |
| image_result.get("confidence", 0) or 0 | |
| ), | |
| "qwen_invoked": bool( | |
| (image_result.get("qwen") or {}).get("invoked") | |
| ), | |
| "qwen_success": bool( | |
| (image_result.get("qwen") or {}).get("success") | |
| ), | |
| "qwen_reason": sanitize_text( | |
| (image_result.get("qwen") or {}).get("reason") | |
| ), | |
| "processing_time_ms": int( | |
| image_result.get("processing_time_ms", 0) or 0 | |
| ), | |
| }, | |
| ) | |
| if row["fallback_triggered"]: | |
| self.neon.execute( | |
| FALLBACK_INSERT, | |
| { | |
| "id": generate_event_id("fb"), | |
| "interaction_id": iid, | |
| "reason": row["fallback_reason"], | |
| "route": row["route"], | |
| "intent": intent, | |
| "confidence": row["intent_confidence"], | |
| "action": "Use official BER information or rephrase.", | |
| }, | |
| ) | |
| success = stored in {"neon", "csv"} | |
| return { | |
| "success": success, | |
| "interaction_id": iid if success else "", | |
| "session_id": session_id, | |
| "stored_in": stored, | |
| "error": None if success else "Analytics persistence unavailable.", | |
| } | |
| def log_feedback( | |
| self, | |
| interaction_id: str, | |
| session_id: str, | |
| rating: str, | |
| comment: str | None = None, | |
| ) -> dict[str, Any]: | |
| rating = rating if rating in VALID_FEEDBACK_RATINGS else "neutral" | |
| clean = sanitize_text(comment) | |
| frustrated = detect_frustration(rating, clean) | |
| row = { | |
| "feedback_id": generate_event_id("feedback"), | |
| "interaction_id": interaction_id, | |
| "session_id": session_id, | |
| "rating": rating, | |
| "comment_sanitized": clean, | |
| "frustration_flag": frustrated, | |
| "created_at": current_utc_iso(), | |
| } | |
| stored = self._store( | |
| FEEDBACK_INSERT, | |
| row, | |
| self.settings.local_feedback_log, | |
| FEEDBACK_FIELDS, | |
| ) | |
| return { | |
| "success": True, | |
| "feedback_id": row["feedback_id"], | |
| "stored_in": stored, | |
| "frustration_flag": frustrated, | |
| "error": None, | |
| } | |
| def log_api_call( | |
| self, | |
| interaction_id: str | None, | |
| provider: str, | |
| api_type: str, | |
| success: bool, | |
| status_code: int | None = None, | |
| duration_ms: int | None = None, | |
| error: str | None = None, | |
| ) -> dict[str, Any]: | |
| row = { | |
| "api_call_id": generate_event_id("api"), | |
| "interaction_id": interaction_id or "", | |
| "provider": sanitize_text(provider), | |
| "api_type": sanitize_text(api_type), | |
| "success": bool(success), | |
| "status_code": "" if status_code is None else status_code, | |
| "duration_ms": "" if duration_ms is None else duration_ms, | |
| "error_sanitized": sanitize_text(error), | |
| "created_at": current_utc_iso(), | |
| } | |
| stored = self._store( | |
| API_CALL_INSERT, | |
| row, | |
| self.settings.local_api_call_log, | |
| API_FIELDS, | |
| ) | |
| return { | |
| "success": True, | |
| "api_call_id": row["api_call_id"], | |
| "stored_in": stored, | |
| "error": None, | |
| } | |
| def export_local_logs(self) -> dict[str, Any]: | |
| return { | |
| "interactions": self.settings.local_interactions_log, | |
| "feedback": self.settings.local_feedback_log, | |
| "api_calls": self.settings.local_api_call_log, | |
| "success": True, | |
| } | |