File size: 3,033 Bytes
1c57887 |
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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
"""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()
# CORS middleware - HTML'den erişim için
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Production'da bunu kısıtla
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()
# Format for dashboard
formatted = {}
for conv in conversations:
# Create a session ID from timestamp
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": []
}
# Add user message
formatted[session_id]["messages"].append({
"type": "received",
"text": conv["user"],
"time": conv["timestamp"]
})
# Add bot response
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)
# Find most asked questions
questions = {}
for conv in conversations:
q = conv["user"].lower()
# Simple categorization
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__":
# This will be imported by Gradio app, not run directly
pass |