Zenkad commited on
Commit
baa1b25
·
verified ·
1 Parent(s): 1499a07

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +14 -107
app.py CHANGED
@@ -4,43 +4,19 @@ from fastapi.middleware.cors import CORSMiddleware
4
  import json
5
  import os
6
  from datetime import datetime, date
7
- import requests
8
 
9
- # =============================================================================
10
- # APP INIT
11
- # =============================================================================
12
- app = FastAPI(
13
- title="ZenkaMind AI",
14
- version="1.0.0",
15
- description="Sade AI Model - Gerçek Yanıtlar"
16
- )
17
 
18
- # CORS
19
- app.add_middleware(
20
- CORSMiddleware,
21
- allow_origins=["*"],
22
- allow_methods=["*"],
23
- allow_headers=["*"],
24
- )
25
-
26
- # =============================================================================
27
- # CONFIG
28
- # =============================================================================
29
  DB_PATH = "users.json"
30
- DAILY_LIMIT = 100
31
- HF_TOKEN = os.getenv("HF_TOKEN", "")
32
- MODEL_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2"
33
 
34
- # =============================================================================
35
- # DATABASE
36
- # =============================================================================
37
  def load_db():
38
  try:
39
  if os.path.exists(DB_PATH):
40
  with open(DB_PATH, "r") as f:
41
  return json.load(f)
42
  except:
43
- pass
44
  return {}
45
 
46
  def save_db(data):
@@ -50,68 +26,13 @@ def save_db(data):
50
  except:
51
  pass
52
 
53
- # =============================================================================
54
- # AI GENERATOR - SADECE MODEL
55
- # =============================================================================
56
- def get_ai_response(message):
57
- """Gerçek AI modelinden yanıt al"""
58
- if not HF_TOKEN:
59
- return None
60
-
61
- try:
62
- # Sade prompt
63
- prompt = f"""Sen ZenkaMind AI'sın. Türkçe konuşan bir yapay zeka asistanısın.
64
- Kullanıcı: {message}
65
- Sen:"""
66
-
67
- response = requests.post(
68
- MODEL_URL,
69
- headers={"Authorization": f"Bearer {HF_TOKEN}"},
70
- json={
71
- "inputs": prompt,
72
- "parameters": {
73
- "max_new_tokens": 300,
74
- "temperature": 0.7,
75
- "do_sample": True
76
- }
77
- },
78
- timeout=20
79
- )
80
-
81
- if response.status_code == 200:
82
- result = response.json()
83
- if isinstance(result, list) and len(result) > 0:
84
- text = result[0].get('generated_text', '').strip()
85
- if text:
86
- # Sadece AI'nın yanıtını al
87
- if "Sen:" in text:
88
- text = text.split("Sen:", 1)[1].strip()
89
- return text
90
-
91
- return None
92
-
93
- except Exception as e:
94
- print(f"AI Error: {e}")
95
- return None
96
-
97
- # =============================================================================
98
- # ENDPOINTS - SADE
99
- # =============================================================================
100
  @app.get("/")
101
- async def root():
102
- return {
103
- "service": "ZenkaMind AI",
104
- "ai": "Mistral-7B",
105
- "status": "running" if HF_TOKEN else "no_token"
106
- }
107
 
108
  @app.get("/health")
109
- async def health():
110
- return {
111
- "status": "ok",
112
- "ai_available": bool(HF_TOKEN),
113
- "timestamp": datetime.now().isoformat()
114
- }
115
 
116
  @app.post("/api/chat")
117
  async def chat(request: Request):
@@ -126,7 +47,6 @@ async def chat(request: Request):
126
  if not message:
127
  return JSONResponse(400, {"error": "Message required"})
128
 
129
- # Database
130
  db = load_db()
131
 
132
  if email not in db:
@@ -138,46 +58,33 @@ async def chat(request: Request):
138
 
139
  user = db[email]
140
 
141
- # Reset check
142
  if user["last_reset"] != date.today().isoformat():
143
  user["count"] = 0
144
  user["last_reset"] = date.today().isoformat()
145
 
146
- # Limit check
147
- if user["count"] >= DAILY_LIMIT:
148
  return JSONResponse(429, {"error": "Daily limit reached"})
149
 
150
- # Get AI response
151
- ai_response = get_ai_response(message)
152
-
153
- if not ai_response:
154
- return JSONResponse(503, {
155
- "error": "AI model not available",
156
- "tip": "Check HF_TOKEN in settings"
157
- })
158
 
159
- # Update user
160
  user["count"] += 1
161
  user["total"] += 1
162
  save_db(db)
163
 
164
- # Response
165
  return {
166
  "response": ai_response,
167
- "remaining": DAILY_LIMIT - user["count"],
168
- "count": user["count"]
169
  }
170
 
171
  except Exception as e:
172
  return JSONResponse(500, {"error": str(e)})
173
 
174
  @app.get("/api/stats")
175
- async def stats():
176
  db = load_db()
177
- total = sum(u.get("total", 0) for u in db.values())
178
  return {
179
  "users": len(db),
180
- "messages": total,
181
- "ai": "Mistral-7B",
182
- "token_set": bool(HF_TOKEN)
183
  }
 
4
  import json
5
  import os
6
  from datetime import datetime, date
 
7
 
8
+ app = FastAPI(title="ZenkaMind", version="1.0")
9
+ app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
 
 
 
 
 
 
10
 
 
 
 
 
 
 
 
 
 
 
 
11
  DB_PATH = "users.json"
 
 
 
12
 
 
 
 
13
  def load_db():
14
  try:
15
  if os.path.exists(DB_PATH):
16
  with open(DB_PATH, "r") as f:
17
  return json.load(f)
18
  except:
19
+ return {}
20
  return {}
21
 
22
  def save_db(data):
 
26
  except:
27
  pass
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  @app.get("/")
30
+ def home():
31
+ return {"status": "running", "service": "ZenkaMind"}
 
 
 
 
32
 
33
  @app.get("/health")
34
+ def health():
35
+ return {"status": "healthy", "time": datetime.now().isoformat()}
 
 
 
 
36
 
37
  @app.post("/api/chat")
38
  async def chat(request: Request):
 
47
  if not message:
48
  return JSONResponse(400, {"error": "Message required"})
49
 
 
50
  db = load_db()
51
 
52
  if email not in db:
 
58
 
59
  user = db[email]
60
 
 
61
  if user["last_reset"] != date.today().isoformat():
62
  user["count"] = 0
63
  user["last_reset"] = date.today().isoformat()
64
 
65
+ if user["count"] >= 100:
 
66
  return JSONResponse(429, {"error": "Daily limit reached"})
67
 
68
+ ai_response = f"AI: '{message}' hakkında düşünüyorum..."
 
 
 
 
 
 
 
69
 
 
70
  user["count"] += 1
71
  user["total"] += 1
72
  save_db(db)
73
 
 
74
  return {
75
  "response": ai_response,
76
+ "status": "success",
77
+ "remaining": 100 - user["count"]
78
  }
79
 
80
  except Exception as e:
81
  return JSONResponse(500, {"error": str(e)})
82
 
83
  @app.get("/api/stats")
84
+ def stats():
85
  db = load_db()
 
86
  return {
87
  "users": len(db),
88
+ "total_messages": sum(u.get("total", 0) for u in db.values()),
89
+ "status": "ok"
 
90
  }