| | """API server for BF conversation tracking""" |
| |
|
| | from fastapi import FastAPI, Response |
| | from fastapi.middleware.cors import CORSMiddleware |
| | import json |
| | import os |
| | from datetime import datetime |
| | from typing import List, Dict, Any |
| | import uvicorn |
| |
|
| | app = FastAPI() |
| |
|
| | |
| | app.add_middleware( |
| | CORSMiddleware, |
| | allow_origins=["*"], |
| | allow_credentials=True, |
| | allow_methods=["*"], |
| | allow_headers=["*"], |
| | ) |
| |
|
| | CONVERSATIONS_FILE = "conversations.json" |
| |
|
| | def load_conversations(): |
| | """Load conversation history from file""" |
| | if os.path.exists(CONVERSATIONS_FILE): |
| | try: |
| | with open(CONVERSATIONS_FILE, 'r', encoding='utf-8') as f: |
| | return json.load(f) |
| | except: |
| | return [] |
| | return [] |
| |
|
| | @app.get("/api/conversations") |
| | async def get_conversations(): |
| | """Get all conversations""" |
| | conversations = load_conversations() |
| | |
| | |
| | formatted = {} |
| | for conv in conversations: |
| | |
| | session_id = f"session_{conv['timestamp'].replace(':', '').replace('-', '').replace('T', '_')[:15]}" |
| | |
| | if session_id not in formatted: |
| | formatted[session_id] = { |
| | "customer": "Kullanıcı", |
| | "phone": session_id, |
| | "messages": [] |
| | } |
| | |
| | |
| | formatted[session_id]["messages"].append({ |
| | "type": "received", |
| | "text": conv["user"], |
| | "time": conv["timestamp"] |
| | }) |
| | |
| | |
| | formatted[session_id]["messages"].append({ |
| | "type": "sent", |
| | "text": conv["bot"], |
| | "time": conv["timestamp"] |
| | }) |
| | |
| | return formatted |
| |
|
| | @app.get("/api/stats") |
| | async def get_stats(): |
| | """Get conversation statistics""" |
| | conversations = load_conversations() |
| | |
| | today = datetime.now().date() |
| | today_count = sum(1 for conv in conversations |
| | if datetime.fromisoformat(conv["timestamp"]).date() == today) |
| | |
| | |
| | questions = {} |
| | for conv in conversations: |
| | q = conv["user"].lower() |
| | |
| | if "madone" in q: |
| | questions["Madone"] = questions.get("Madone", 0) + 1 |
| | elif "marlin" in q: |
| | questions["Marlin"] = questions.get("Marlin", 0) + 1 |
| | elif "fiyat" in q or "kaç" in q: |
| | questions["Fiyat"] = questions.get("Fiyat", 0) + 1 |
| | elif "stok" in q or "var mı" in q: |
| | questions["Stok"] = questions.get("Stok", 0) + 1 |
| | |
| | return { |
| | "total": len(conversations), |
| | "today": today_count, |
| | "categories": questions |
| | } |
| |
|
| | @app.get("/api/health") |
| | async def health_check(): |
| | """Health check endpoint""" |
| | return {"status": "ok", "timestamp": datetime.now().isoformat()} |
| |
|
| | if __name__ == "__main__": |
| | |
| | pass |