from pymongo import MongoClient import pandas as pd import plotly.graph_objects as go import time import random class MongoDataFrameLoader: def __init__(self, uri, db_name , collection_name): self.uri = uri self.database_name = db_name self.collection_name = collection_name self.client = MongoClient(uri) self.db = self.client[self.database_name] self.collection = self.db[self.collection_name] def load_dataframe(self, df): try: if df.empty: print("Provided DataFrame is empty. No data inserted.") return data = df.to_dict(orient="records") result = self.collection.insert_many(data) print(f"Inserted {len(result.inserted_ids)} documents into '{self.collection_name}' collection.") except Exception as e: print(f"Error inserting DataFrame: {e}") def get_random_email_pair(self): # Step 1: Get all distinct email IDs email_ids = self.collection.distinct("email") if len(email_ids) < 1: raise ValueError("No email records found in the collection.") # Step 2: Pick one random email ID random_emailid = random.choice(email_ids) # Step 3: Fetch all documents for that email ID records = list(self.collection.find({"email": random_emailid})) if len(records) < 2: raise ValueError(f"Not enough model records for email '{random_emailid}'") # Step 4: Randomly pick two model variants model_a_record, model_b_record = random.sample(records, 2) # Step 5: Identify common email_X keys available_keys = [f"Email_{i}" for i in range(1, 9)] valid_keys = [key for key in available_keys if key in model_a_record and key in model_b_record] if not valid_keys: raise ValueError(f"No shared email keys (email_1 to email_8) found for '{random_emailid}'") # Step 6: Randomly select one of them email_key = random.choice(valid_keys) email_position = email_key.split("_")[1] # Step 7: Build and return response return { "prospect_email": random_emailid, "prospect_company": model_a_record.get("Company Name"), "email_position": email_position, "model_a": model_a_record.get("LLM_Model"), "email_a_content": model_a_record[email_key], "model_b": model_b_record.get("LLM_Model"), "email_b_content": model_b_record[email_key] } def save_ab_test_result(self, test_data: dict, choice: str): winner = "skip" if choice == "left": winner = test_data["model_a"] elif choice == "right": winner = test_data["model_b"] document = { "prospect_email": test_data["prospect_email"], "models_compared": [test_data["model_a"], test_data["model_b"]], "winner": winner, "email_position": test_data["email_position"], "timestamp": time.time() } self.collection.insert_one(document) print(f"✅ Vote saved to MongoDB: {test_data['model_a']} vs {test_data['model_b']}, Winner: {winner}") def get_analytics_data(self): results = list(self.collection.find()) if not results: return {"win_rates": {}, "position_performance": {}, "one_v_one": {}} wins, total_games = {}, {} pos_wins, pos_total = {i: {} for i in range(1, 9)}, {i: {} for i in range(1, 9)} all_models = set() for r in results: m_a, m_b = r["models_compared"] all_models.update([m_a, m_b]) total_games[m_a] = total_games.get(m_a, 0) + 1 total_games[m_b] = total_games.get(m_b, 0) + 1 if r["winner"] != "skip": wins[r["winner"]] = wins.get(r["winner"], 0) + 1 pos = int(r["email_position"]) pos_total[pos][m_a] = pos_total[pos].get(m_a, 0) + 1 pos_total[pos][m_b] = pos_total[pos].get(m_b, 0) + 1 if r["winner"] != "skip": pos_wins[pos][r["winner"]] = pos_wins[pos].get(r["winner"], 0) + 1 win_rates = {m: (wins.get(m, 0) / total_games[m]) * 100 for m in total_games} pos_perf = { m: [(pos_wins[i].get(m, 0) / pos_total[i].get(m, 1)) * 100 for i in range(1, 9)] for m in all_models } # 1-vs-1 Win Rate Matrix one_v_one = {m: {m2: {"wins": 0, "total": 0} for m2 in all_models} for m in all_models} for r in results: if r["winner"] == "skip": continue winner = r["winner"] loser = next(m for m in r["models_compared"] if m != winner) one_v_one[winner][loser]["wins"] += 1 one_v_one[winner][loser]["total"] += 1 one_v_one[loser][winner]["total"] += 1 return { "win_rates": win_rates, "position_performance": pos_perf, "one_v_one": one_v_one, "all_models": sorted(list(all_models)) } def find_all(self): return list(self.collection.find()) def insert_one(self, data_dict): return self.collection.insert_one(data_dict) def close(self): self.client.close()