from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel from typing import Dict, Optional import networkx as nx from datetime import datetime # Initialize FastAPI app app = FastAPI( title="Connect Friend API", description="API for analyzing connection strength between friends", version="1.0.0" ) # Enable CORS app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Pydantic models class ConnectionRequest(BaseModel): user_id: str friend_id: str interaction_data: Optional[Dict] = None class ConnectionStrengthResponse(BaseModel): user_id: str friend_id: str connection_strength: float confidence_score: float last_updated: str metrics: Optional[Dict] = {} # Graph G = nx.Graph() def initialize_model(): G.add_edges_from([ ('user1', 'user2', {'weight': 0.8}), ('user1', 'user3', {'weight': 0.6}), ('user2', 'user3', {'weight': 0.9}), ]) def calculate_connection_strength(user_id: str, friend_id: str) -> Dict: if not G.has_node(user_id) or not G.has_node(friend_id): return {"connection_strength": 0.0, "confidence_score": 0.0, "metrics": {}} try: common_neighbors = len(list(nx.common_neighbors(G, user_id, friend_id))) jaccard = next(nx.jaccard_coefficient(G, [(user_id, friend_id)]))[2] pref_attachment = next(nx.preferential_attachment(G, [(user_id, friend_id)]))[2] connection_strength = (jaccard * 0.4) + (pref_attachment * 0.3) + (common_neighbors * 0.1) return { "connection_strength": min(max(round(connection_strength, 2), 0.0), 1.0), "confidence_score": 0.95, "metrics": { "common_neighbors": common_neighbors, "jaccard_similarity": round(jaccard, 3), "preferential_attachment": round(pref_attachment, 3) } } except Exception: return {"connection_strength": 0.0, "confidence_score": 0.0, "metrics": {}} @app.get("/") async def root(): return {"message": "Welcome to Connect Friend API. Use /docs for API documentation."} @app.post("/api/connection-strength", response_model=ConnectionStrengthResponse) async def get_connection_strength(connection: ConnectionRequest): if connection.interaction_data: if G.has_edge(connection.user_id, connection.friend_id): G[connection.user_id][connection.friend_id]['weight'] = min( G[connection.user_id][connection.friend_id].get('weight', 0) + 0.1, 1.0 ) else: G.add_edge(connection.user_id, connection.friend_id, weight=0.5) metrics = calculate_connection_strength(connection.user_id, connection.friend_id) return { "user_id": connection.user_id, "friend_id": connection.friend_id, "connection_strength": metrics["connection_strength"], "confidence_score": metrics["confidence_score"], "last_updated": datetime.utcnow().isoformat(), "metrics": metrics["metrics"] } @app.get("/api/user/{user_id}/suggestions") async def get_connection_suggestions(user_id: str, limit: int = 5): if not G.has_node(user_id): return {"suggestions": [], "message": "User not found in the network"} suggestions, seen = [], {user_id} for friend in G.neighbors(user_id): seen.add(friend) for fof in G.neighbors(friend): if fof not in seen and not G.has_edge(user_id, fof): metrics = calculate_connection_strength(user_id, fof) suggestions.append({ "user_id": fof, "connection_score": metrics["connection_strength"], "common_connections": metrics["metrics"].get("common_neighbors", 0) }) suggestions = sorted(suggestions, key=lambda x: x["connection_score"], reverse=True)[:limit] return {"suggestions": suggestions} initialize_model()