Spaces:
Sleeping
Sleeping
Download src/utils/feedback.py from faseehsandhu/Digitalytics: direct link, hf CLI and curl.
- Browser
- Download file 8.41 kB
-
https://huggingface.co/spaces/faseehsandhu/Digitalytics/resolve/main/src/utils/feedback.py
- Command line
-
hf download hf://spaces/faseehsandhu/Digitalytics/src/utils/feedback.py
-
curl -L -o feedback.py https://huggingface.co/spaces/faseehsandhu/Digitalytics/resolve/main/src/utils/feedback.py
8.41 kB
| """ | |
| Feedback collection and analytics for continuous improvement. | |
| Tracks user feedback on response quality to identify areas for improvement | |
| and measure overall system performance. | |
| """ | |
| import json | |
| from pathlib import Path | |
| from datetime import datetime | |
| from typing import Dict, List, Optional | |
| class FeedbackCollector: | |
| """Collects and analyzes user feedback.""" | |
| def __init__(self, feedback_dir: str = ".feedback"): | |
| """ | |
| Initialize feedback collector. | |
| Args: | |
| feedback_dir: Directory to store feedback files | |
| """ | |
| self.feedback_dir = Path(feedback_dir) | |
| # Ensure feedback directory exists even if parent path is missing | |
| self.feedback_dir.mkdir(parents=True, exist_ok=True) | |
| self.feedback_file = self.feedback_dir / "feedback.jsonl" | |
| def collect_feedback( | |
| self, | |
| query: str, | |
| response: str, | |
| rating: int | |
| ) -> bool: | |
| """ | |
| Record user feedback on a response. | |
| Args: | |
| query: User's original query | |
| response: AI response provided | |
| rating: User rating (1-5 stars) | |
| Returns: | |
| True if feedback was recorded successfully | |
| """ | |
| try: | |
| # Ensure directory still exists (in case it was deleted while app runs) | |
| self.feedback_dir.mkdir(parents=True, exist_ok=True) | |
| # Validate rating | |
| if not 1 <= rating <= 5: | |
| return False | |
| feedback = { | |
| "timestamp": datetime.now().isoformat(), | |
| "query": query[:500], # Truncate to avoid huge logs | |
| "response": response[:500], | |
| "rating": rating, | |
| "useful": rating >= 4, # Define "useful" as 4+ stars | |
| } | |
| # Append to JSONL file (one JSON object per line) | |
| with open(self.feedback_file, 'a', encoding='utf-8') as f: | |
| f.write(json.dumps(feedback) + "\n") | |
| return True | |
| except Exception as e: | |
| print(f"Error recording feedback: {e}") | |
| return False | |
| def get_all_feedback(self) -> List[Dict]: | |
| """ | |
| Retrieve all recorded feedback. | |
| Returns: | |
| List of feedback dictionaries | |
| """ | |
| if not self.feedback_file.exists(): | |
| return [] | |
| feedbacks = [] | |
| try: | |
| with open(self.feedback_file, 'r', encoding='utf-8') as f: | |
| for line in f: | |
| line = line.strip() | |
| if line: | |
| feedbacks.append(json.loads(line)) | |
| except Exception as e: | |
| print(f"Error reading feedback: {e}") | |
| return feedbacks | |
| def get_feedback_stats(self) -> Dict: | |
| """ | |
| Get summary statistics about feedback. | |
| Returns: | |
| Dictionary with feedback metrics | |
| """ | |
| feedbacks = self.get_all_feedback() | |
| if not feedbacks: | |
| return { | |
| "total": 0, | |
| "avg_rating": 0.0, | |
| "useful_pct": 0.0, | |
| "rating_distribution": {}, | |
| "last_updated": None | |
| } | |
| ratings = [f["rating"] for f in feedbacks] | |
| useful = sum(1 for f in feedbacks if f["useful"]) | |
| # Get distribution by rating | |
| distribution = {} | |
| for i in range(1, 6): | |
| count = sum(1 for r in ratings if r == i) | |
| distribution[i] = count | |
| # Get distribution by retrieval source | |
| sources = {} | |
| for f in feedbacks: | |
| source = f.get("retrieval_source", "unknown") | |
| sources[source] = sources.get(source, 0) + 1 | |
| return { | |
| "total": len(feedbacks), | |
| "avg_rating": sum(ratings) / len(ratings), | |
| "useful_pct": (useful / len(feedbacks)) * 100, | |
| "rating_distribution": distribution, | |
| "source_distribution": sources, | |
| "last_updated": datetime.now().isoformat() | |
| } | |
| def get_low_quality_feedback(self, rating_threshold: int = 2) -> List[Dict]: | |
| """ | |
| Get feedback for low-quality responses to identify improvement areas. | |
| Args: | |
| rating_threshold: Only return feedback below this rating | |
| Returns: | |
| List of low-rating feedback items | |
| """ | |
| feedbacks = self.get_all_feedback() | |
| return [f for f in feedbacks if f["rating"] <= rating_threshold] | |
| def get_feedback_by_session(self, session_id: str) -> List[Dict]: | |
| """ | |
| Get all feedback from a specific session. | |
| Args: | |
| session_id: Session identifier | |
| Returns: | |
| List of feedback from that session | |
| """ | |
| feedbacks = self.get_all_feedback() | |
| return [f for f in feedbacks if f.get("session_id") == session_id] | |
| def export_feedback_csv(self, output_path: str) -> bool: | |
| """ | |
| Export feedback to CSV for analysis. | |
| Args: | |
| output_path: Path to write CSV file | |
| Returns: | |
| True if export successful | |
| """ | |
| try: | |
| import csv | |
| feedbacks = self.get_all_feedback() | |
| if not feedbacks: | |
| return False | |
| with open(output_path, 'w', newline='', encoding='utf-8') as f: | |
| writer = csv.DictWriter(f, fieldnames=feedbacks[0].keys()) | |
| writer.writeheader() | |
| writer.writerows(feedbacks) | |
| return True | |
| except Exception as e: | |
| print(f"Error exporting feedback: {e}") | |
| return False | |
| def get_trending_issues(self, min_feedback: int = 5) -> List[Dict]: | |
| """ | |
| Identify recurring issues from low-quality feedback. | |
| Looks for common patterns in negative feedback to identify | |
| systemic problems with the system. | |
| Args: | |
| min_feedback: Minimum feedback count to report a trend | |
| Returns: | |
| List of potential issues with frequency counts | |
| """ | |
| low_feedback = self.get_low_quality_feedback(rating_threshold=2) | |
| if len(low_feedback) < min_feedback: | |
| return [] | |
| # Look for common keywords in negative feedback | |
| issues = {} | |
| keywords = [ | |
| "not relevant", "wrong", "inaccurate", "confused", | |
| "missing", "unclear", "poor", "bad", "unhelpful", | |
| "too long", "too short", "error", "crash", "timeout" | |
| ] | |
| for feedback in low_feedback: | |
| text = (feedback.get("feedback_text", "") + " " + feedback.get("query", "")).lower() | |
| for keyword in keywords: | |
| if keyword in text: | |
| issues[keyword] = issues.get(keyword, 0) + 1 | |
| # Return sorted by frequency | |
| return [ | |
| {"issue": issue, "count": count} | |
| for issue, count in sorted(issues.items(), key=lambda x: x[1], reverse=True) | |
| ] | |
| def clear_old_feedback(self, days: int = 30) -> int: | |
| """ | |
| Remove feedback older than N days. | |
| Args: | |
| days: Age threshold in days | |
| Returns: | |
| Number of feedback items removed | |
| """ | |
| try: | |
| from datetime import timedelta | |
| feedbacks = self.get_all_feedback() | |
| cutoff = datetime.now() - timedelta(days=days) | |
| retained = [] | |
| removed = 0 | |
| for f in feedbacks: | |
| timestamp = datetime.fromisoformat(f["timestamp"]) | |
| if timestamp >= cutoff: | |
| retained.append(f) | |
| else: | |
| removed += 1 | |
| # Write back retained feedback | |
| with open(self.feedback_file, 'w', encoding='utf-8') as f: | |
| for feedback in retained: | |
| f.write(json.dumps(feedback) + "\n") | |
| return removed | |
| except Exception as e: | |
| print(f"Error clearing old feedback: {e}") | |
| return 0 | |