File size: 2,388 Bytes
3214b6b
aada386
4cca9d6
 
07d5c76
e42fcaf
b54253f
4cca9d6
aada386
 
 
b54253f
aada386
 
 
8e0fcfe
b54253f
4cca9d6
ce72c52
3214b6b
aada386
 
 
b54253f
 
 
 
 
aada386
 
b54253f
 
 
aada386
b54253f
aada386
54f7978
b54253f
07d5c76
b54253f
aada386
b54253f
aada386
07d5c76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57d4fb8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
from datetime import datetime
import firebase_admin
from firebase_admin import credentials, firestore
from collections import defaultdict

# πŸ” Initialize Firebase (only once)
if not firebase_admin._apps:
    try:
        cred = credentials.Certificate("firebase_key.json")
        firebase_admin.initialize_app(cred)
        print("βœ… Firebase connection established.")
    except Exception as e:
        print(f"❌ Firebase initialization failed: {e}")
        raise

# === Firestore client
db = firestore.client()

def log_user_feedback(goal, sol1, sol2, winner):
    try:
        formatted_winner = "1" if "1" in winner else "2"

        # Basic input sanitation
        goal = goal.strip()[:500]
        sol1 = sol1.strip()[:500]
        sol2 = sol2.strip()[:500]

        doc = {
            "timestamp": datetime.utcnow().isoformat(),
            "goal": goal,
            "solution_1": sol1,
            "solution_2": sol2,
            "winner": formatted_winner,
            "user_feedback": "from app.py",
        }

        ref = db.collection("evo_feedback").add(doc)
        print(f"πŸ“… Feedback logged (ID: {ref[1].id}) β€” Winner: Solution {formatted_winner}")

    except Exception as e:
        print(f"❌ Feedback logging failed: {e}")
        raise

def get_goal_leaderboard(top_n=5):
    try:
        # Query all feedback docs
        feedback_docs = db.collection("evo_feedback").stream()
        goal_counter = defaultdict(int)

        for doc in feedback_docs:
            data = doc.to_dict()
            goal = data.get("goal", "").strip()
            if goal:
                goal_counter[goal] += 1

        # Sort by count, descending
        sorted_goals = sorted(goal_counter.items(), key=lambda x: x[1], reverse=True)
        return sorted_goals[:top_n]

    except Exception as e:
        print(f"❌ Failed to load leaderboard: {e}")
        return []

def get_vote_counts():
    try:
        docs = db.collection("evo_feedback").stream()
        count_1, count_2 = 0, 0

        for doc in docs:
            winner = doc.to_dict().get("winner", "").strip()
            if winner == "1":
                count_1 += 1
            elif winner == "2":
                count_2 += 1

        return {"1": count_1, "2": count_2}
    except Exception as e:
        print(f"❌ Failed to get vote counts: {e}")
        return {"1": 0, "2": 0}