Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,21 +1,21 @@
|
|
| 1 |
from fastapi import FastAPI, Request
|
| 2 |
from fastapi.responses import JSONResponse
|
| 3 |
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
| 4 |
import os
|
| 5 |
-
import
|
|
|
|
| 6 |
|
| 7 |
-
#
|
| 8 |
-
#
|
| 9 |
-
#
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
# FASTAPI
|
| 16 |
-
# =========================
|
| 17 |
-
app = FastAPI(title="ZenkaMind API")
|
| 18 |
|
|
|
|
| 19 |
app.add_middleware(
|
| 20 |
CORSMiddleware,
|
| 21 |
allow_origins=["*"],
|
|
@@ -23,63 +23,274 @@ app.add_middleware(
|
|
| 23 |
allow_headers=["*"],
|
| 24 |
)
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
message = data.get("message", "").strip()
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
except Exception as e:
|
| 85 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from fastapi import FastAPI, Request
|
| 2 |
from fastapi.responses import JSONResponse
|
| 3 |
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
+
import json
|
| 5 |
import os
|
| 6 |
+
import random
|
| 7 |
+
from datetime import datetime, date
|
| 8 |
|
| 9 |
+
# =============================================================================
|
| 10 |
+
# APP INIT
|
| 11 |
+
# =============================================================================
|
| 12 |
+
app = FastAPI(
|
| 13 |
+
title="ZenkaMind API",
|
| 14 |
+
version="1.0.0",
|
| 15 |
+
description="ZenkaMind AI Asistan API"
|
| 16 |
+
)
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
+
# CORS
|
| 19 |
app.add_middleware(
|
| 20 |
CORSMiddleware,
|
| 21 |
allow_origins=["*"],
|
|
|
|
| 23 |
allow_headers=["*"],
|
| 24 |
)
|
| 25 |
|
| 26 |
+
# =============================================================================
|
| 27 |
+
# CONFIG
|
| 28 |
+
# =============================================================================
|
| 29 |
+
DB_PATH = "users.json"
|
| 30 |
+
FREE_DAILY_LIMIT = 30
|
| 31 |
+
PREMIUM_PRICE = 499
|
| 32 |
+
SHOPIER_LINK = "https://shopier.com/42153760"
|
|
|
|
| 33 |
|
| 34 |
+
# =============================================================================
|
| 35 |
+
# DATABASE
|
| 36 |
+
# =============================================================================
|
| 37 |
+
def load_db():
|
| 38 |
+
"""Veritabanını yükle"""
|
| 39 |
+
try:
|
| 40 |
+
if os.path.exists(DB_PATH):
|
| 41 |
+
with open(DB_PATH, "r", encoding="utf-8") as f:
|
| 42 |
+
return json.load(f)
|
| 43 |
+
except:
|
| 44 |
+
pass
|
| 45 |
+
return {}
|
| 46 |
|
| 47 |
+
def save_db(data):
|
| 48 |
+
"""Veritabanını kaydet"""
|
| 49 |
+
try:
|
| 50 |
+
with open(DB_PATH, "w", encoding="utf-8") as f:
|
| 51 |
+
json.dump(data, f, indent=2, ensure_ascii=False)
|
| 52 |
+
except:
|
| 53 |
+
pass
|
| 54 |
|
| 55 |
+
# =============================================================================
|
| 56 |
+
# AI RESPONSES
|
| 57 |
+
# =============================================================================
|
| 58 |
+
class AIResponder:
|
| 59 |
+
def __init__(self):
|
| 60 |
+
self.responses = {
|
| 61 |
+
"greeting": [
|
| 62 |
+
"Merhaba! Ben ZenkaMind AI. Size nasıl yardımcı olabilirim? 🤖",
|
| 63 |
+
"Hoş geldiniz! ZenkaMind AI asistanınız burada. 💫",
|
| 64 |
+
"Selam! Bugün sizin için nasıl faydalı olabilirim? ✨"
|
| 65 |
+
],
|
| 66 |
+
"help": [
|
| 67 |
+
"Size yardımcı olmak için buradayım. Sorunuz nedir? 📝",
|
| 68 |
+
"Hangi konuda destek almak istiyorsunuz? 🔍",
|
| 69 |
+
"Sorunuzu anlatın, en iyi çözümü bulalım. 💡"
|
| 70 |
+
],
|
| 71 |
+
"business": [
|
| 72 |
+
"Freelance işler için: Portföy oluşturun, net fiyat belirleyin. 💼",
|
| 73 |
+
"Müşteri bulma: Networking, referans, portfolio önemli. 📈",
|
| 74 |
+
"Proje yönetimi: Deadline'lara sadık kalın, iletişimi açık tutun. 🗓️"
|
| 75 |
+
],
|
| 76 |
+
"general": [
|
| 77 |
+
"İlginç bir konu! Biraz daha açıklayabilir misiniz? 🤔",
|
| 78 |
+
"Bu konuda size yardımcı olabilirim. 📚",
|
| 79 |
+
"Anladım. Size nasıl destek olabilirim? 💭"
|
| 80 |
+
]
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
def generate(self, message, is_premium=False):
|
| 84 |
+
"""Yanıt oluştur"""
|
| 85 |
+
msg_lower = message.lower()
|
| 86 |
+
|
| 87 |
+
# Kategori belirle
|
| 88 |
+
if any(word in msg_lower for word in ["merhaba", "selam", "hi", "hello"]):
|
| 89 |
+
category = "greeting"
|
| 90 |
+
elif any(word in msg_lower for word in ["yardım", "help", "nasıl", "yapayım"]):
|
| 91 |
+
category = "help"
|
| 92 |
+
elif any(word in msg_lower for word in ["iş", "business", "para", "kazan", "freelance"]):
|
| 93 |
+
category = "business"
|
| 94 |
+
else:
|
| 95 |
+
category = "general"
|
| 96 |
+
|
| 97 |
+
# Yanıt seç
|
| 98 |
+
response = random.choice(self.responses[category])
|
| 99 |
+
|
| 100 |
+
# Premium teşvik
|
| 101 |
+
if not is_premium:
|
| 102 |
+
response += f"\n\n💎 **Premium ile daha iyi yanıtlar:** {SHOPIER_LINK}"
|
| 103 |
+
|
| 104 |
+
return response
|
| 105 |
|
| 106 |
+
# =============================================================================
|
| 107 |
+
# ENDPOINTS
|
| 108 |
+
# =============================================================================
|
| 109 |
+
ai = AIResponder()
|
| 110 |
|
| 111 |
+
@app.get("/")
|
| 112 |
+
async def root():
|
| 113 |
+
return {
|
| 114 |
+
"service": "ZenkaMind API",
|
| 115 |
+
"version": "1.0.0",
|
| 116 |
+
"status": "running",
|
| 117 |
+
"endpoints": {
|
| 118 |
+
"chat": "POST /api/chat",
|
| 119 |
+
"health": "GET /health",
|
| 120 |
+
"stats": "GET /api/stats"
|
| 121 |
+
}
|
| 122 |
}
|
| 123 |
|
| 124 |
+
@app.get("/health")
|
| 125 |
+
async def health():
|
| 126 |
+
return {
|
| 127 |
+
"status": "healthy",
|
| 128 |
+
"timestamp": datetime.now().isoformat(),
|
| 129 |
+
"service": "ZenkaMind API"
|
|
|
|
|
|
|
| 130 |
}
|
| 131 |
|
| 132 |
+
@app.post("/api/chat")
|
| 133 |
+
async def chat(request: Request):
|
| 134 |
try:
|
| 135 |
+
# JSON verisini al
|
| 136 |
+
data = await request.json()
|
| 137 |
+
email = data.get("email", "").strip().lower()
|
| 138 |
+
message = data.get("message", "").strip()
|
| 139 |
+
|
| 140 |
+
# Validasyon
|
| 141 |
+
if not email or "@" not in email:
|
| 142 |
+
return JSONResponse(
|
| 143 |
+
status_code=400,
|
| 144 |
+
content={"error": "Geçerli email adresi gerekli"}
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
if not message:
|
| 148 |
+
return JSONResponse(
|
| 149 |
+
status_code=400,
|
| 150 |
+
content={"error": "Mesaj boş olamaz"}
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
# Veritabanını yükle
|
| 154 |
+
db = load_db()
|
| 155 |
+
|
| 156 |
+
# Kullanıcı kontrolü
|
| 157 |
+
if email not in db:
|
| 158 |
+
db[email] = {
|
| 159 |
+
"premium": False,
|
| 160 |
+
"daily_count": 0,
|
| 161 |
+
"total_messages": 0,
|
| 162 |
+
"created_at": datetime.now().isoformat(),
|
| 163 |
+
"last_reset": date.today().isoformat()
|
| 164 |
}
|
| 165 |
+
|
| 166 |
+
user = db[email]
|
| 167 |
+
is_premium = user["premium"]
|
| 168 |
+
|
| 169 |
+
# Günlük reset kontrolü
|
| 170 |
+
today = date.today().isoformat()
|
| 171 |
+
if user["last_reset"] != today:
|
| 172 |
+
user["daily_count"] = 0
|
| 173 |
+
user["last_reset"] = today
|
| 174 |
+
|
| 175 |
+
# Limit kontrolü (free kullanıcılar için)
|
| 176 |
+
if not is_premium and user["daily_count"] >= FREE_DAILY_LIMIT:
|
| 177 |
+
return JSONResponse(
|
| 178 |
+
status_code=402,
|
| 179 |
+
content={
|
| 180 |
+
"response": f"""
|
| 181 |
+
🚫 **GÜNLÜK LİMİT DOLDU**
|
| 182 |
|
| 183 |
+
Bugün {user['daily_count']}/{FREE_DAILY_LIMIT} mesaj kullandınız.
|
| 184 |
|
| 185 |
+
💎 **Premium avantajları:**
|
| 186 |
+
✓ Sınırsız mesaj
|
| 187 |
+
✓ Gelişmiş AI
|
| 188 |
+
✓ Özel destek
|
| 189 |
+
|
| 190 |
+
🔗 **Hemen başlayın:** {SHOPIER_LINK}
|
| 191 |
+
""",
|
| 192 |
+
"status": "limit_exceeded",
|
| 193 |
+
"premium": False
|
| 194 |
+
}
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
# AI yanıtı oluştur
|
| 198 |
+
ai_response = ai.generate(message, is_premium)
|
| 199 |
+
|
| 200 |
+
# Mesaj sayacını artır
|
| 201 |
+
user["daily_count"] += 1
|
| 202 |
+
user["total_messages"] += 1
|
| 203 |
+
|
| 204 |
+
# Veritabanını kaydet
|
| 205 |
+
save_db(db)
|
| 206 |
+
|
| 207 |
+
# Kalan mesaj hesapla
|
| 208 |
+
remaining = FREE_DAILY_LIMIT - user["daily_count"] if not is_premium else "unlimited"
|
| 209 |
+
|
| 210 |
+
# Başarılı yanıt
|
| 211 |
+
return {
|
| 212 |
+
"response": ai_response,
|
| 213 |
+
"status": "success",
|
| 214 |
+
"premium": is_premium,
|
| 215 |
+
"user_info": {
|
| 216 |
+
"email": email,
|
| 217 |
+
"plan": "premium" if is_premium else "free",
|
| 218 |
+
"limits": {
|
| 219 |
+
"daily_limit": FREE_DAILY_LIMIT,
|
| 220 |
+
"used_today": user["daily_count"],
|
| 221 |
+
"remaining": remaining
|
| 222 |
+
},
|
| 223 |
+
"total_messages": user["total_messages"]
|
| 224 |
+
}
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
except json.JSONDecodeError:
|
| 228 |
+
return JSONResponse(
|
| 229 |
+
status_code=400,
|
| 230 |
+
content={"error": "Geçersiz JSON formatı"}
|
| 231 |
+
)
|
| 232 |
+
except Exception as e:
|
| 233 |
+
return JSONResponse(
|
| 234 |
+
status_code=500,
|
| 235 |
+
content={"error": f"Sunucu hatası: {str(e)}"}
|
| 236 |
+
)
|
| 237 |
|
| 238 |
+
@app.get("/api/stats")
|
| 239 |
+
async def stats():
|
| 240 |
+
db = load_db()
|
| 241 |
+
|
| 242 |
+
premium_count = sum(1 for user in db.values() if user.get("premium", False))
|
| 243 |
+
total_messages = sum(user.get("total_messages", 0) for user in db.values())
|
| 244 |
+
|
| 245 |
+
return {
|
| 246 |
+
"total_users": len(db),
|
| 247 |
+
"premium_users": premium_count,
|
| 248 |
+
"free_users": len(db) - premium_count,
|
| 249 |
+
"total_messages": total_messages,
|
| 250 |
+
"daily_limit": FREE_DAILY_LIMIT,
|
| 251 |
+
"premium_price": PREMIUM_PRICE,
|
| 252 |
+
"status": "active"
|
| 253 |
+
}
|
| 254 |
|
| 255 |
+
@app.post("/api/user/info")
|
| 256 |
+
async def user_info(request: Request):
|
| 257 |
+
try:
|
| 258 |
+
data = await request.json()
|
| 259 |
+
email = data.get("email", "").strip().lower()
|
| 260 |
+
|
| 261 |
+
if not email or "@" not in email:
|
| 262 |
+
return JSONResponse(
|
| 263 |
+
status_code=400,
|
| 264 |
+
content={"error": "Geçerli email gerekli"}
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
db = load_db()
|
| 268 |
+
|
| 269 |
+
if email not in db:
|
| 270 |
+
return JSONResponse(
|
| 271 |
+
status_code=404,
|
| 272 |
+
content={"error": "Kullanıcı bulunamadı"}
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
user = db[email]
|
| 276 |
+
is_premium = user["premium"]
|
| 277 |
+
remaining = FREE_DAILY_LIMIT - user["daily_count"] if not is_premium else "unlimited"
|
| 278 |
+
|
| 279 |
+
return {
|
| 280 |
+
"email": email,
|
| 281 |
+
"premium": is_premium,
|
| 282 |
+
"plan": "premium" if is_premium else "free",
|
| 283 |
+
"limits": {
|
| 284 |
+
"daily_limit": FREE_DAILY_LIMIT,
|
| 285 |
+
"used_today": user["daily_count"],
|
| 286 |
+
"remaining": remaining
|
| 287 |
+
},
|
| 288 |
+
"total_messages": user.get("total_messages", 0),
|
| 289 |
+
"created_at": user.get("created_at")
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
except Exception as e:
|
| 293 |
+
return JSONResponse(
|
| 294 |
+
status_code=500,
|
| 295 |
+
content={"error": str(e)}
|
| 296 |
+
)
|