Zenkad commited on
Commit
0912d9c
·
verified ·
1 Parent(s): c6ccd8f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -152
app.py CHANGED
@@ -3,18 +3,16 @@ from fastapi.responses import JSONResponse
3
  from fastapi.middleware.cors import CORSMiddleware
4
  import json
5
  import os
6
- import random
7
- import time
8
  from datetime import datetime, date
9
- import requests # Gerçek AI için
10
 
11
  # =============================================================================
12
  # APP INIT
13
  # =============================================================================
14
  app = FastAPI(
15
- title="ZenkaMind AI API",
16
- version="3.0.0",
17
- description="Gerçek AI Model ile ZenkaMind"
18
  )
19
 
20
  # CORS
@@ -29,9 +27,9 @@ app.add_middleware(
29
  # CONFIG
30
  # =============================================================================
31
  DB_PATH = "users.json"
32
- DAILY_LIMIT = 50
33
  HF_TOKEN = os.getenv("HF_TOKEN", "")
34
- HF_API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2"
35
 
36
  # =============================================================================
37
  # DATABASE
@@ -39,7 +37,7 @@ HF_API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-I
39
  def load_db():
40
  try:
41
  if os.path.exists(DB_PATH):
42
- with open(DB_PATH, "r", encoding="utf-8") as f:
43
  return json.load(f)
44
  except:
45
  pass
@@ -47,132 +45,72 @@ def load_db():
47
 
48
  def save_db(data):
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
- # REAL AI GENERATOR
57
  # =============================================================================
58
- class RealAIGenerator:
59
- def __init__(self):
60
- self.hf_token = HF_TOKEN
61
- self.headers = {"Authorization": f"Bearer {self.hf_token}"} if self.hf_token else {}
62
- print(f"🤖 AI Mode: {'REAL' if self.hf_token else 'FALLBACK'}")
63
 
64
- def get_real_ai_response(self, message):
65
- """Gerçek Hugging Face API'den yanıt al"""
66
- if not self.hf_token:
67
- return None
68
-
69
- try:
70
- prompt = f"""Sen ZenkaMind AI'sın. Türkçe konuşan bir yapay zeka asistanısın.
71
  Kullanıcı: {message}
72
- AI:"""
73
-
74
- response = requests.post(
75
- HF_API_URL,
76
- headers=self.headers,
77
- json={
78
- "inputs": prompt,
79
- "parameters": {
80
- "max_new_tokens": 200,
81
- "temperature": 0.7,
82
- "return_full_text": False
83
- }
84
- },
85
- timeout=30
86
- )
87
-
88
- if response.status_code == 200:
89
- result = response.json()
90
- if isinstance(result, list) and len(result) > 0:
91
- text = result[0].get('generated_text', '').strip()
92
- if text and len(text) > 10:
93
- return text
94
-
95
- except Exception as e:
96
- print(f"Real AI Error: {e}")
97
 
98
  return None
99
-
100
- def generate_response(self, message):
101
- """Önce gerçek AI, olmazsa akıllı yanıt"""
102
- # 1. Gerçek AI deneyelim
103
- real_response = self.get_real_ai_response(message)
104
-
105
- if real_response:
106
- return f"🤖 **Gerçek AI Yanıtı:**\n{real_response}"
107
-
108
- # 2. Akıllı fallback (hazır yanıt DEĞİL, mesaja göre yanıt)
109
- return self.create_smart_response(message)
110
-
111
- def create_smart_response(self, message):
112
- """Mesaja göre akıllı yan��t oluştur"""
113
- msg = message.lower()
114
-
115
- # Mesaj analizi
116
- if "merhaba" in msg or "selam" in msg:
117
- return "🤖 Merhaba! Ben ZenkaMind AI. Size nasıl yardımcı olabilirim?"
118
-
119
- elif "nasılsın" in msg:
120
- return "🤖 Teşekkür ederim! Ben bir AI olarak her zaman hazırım. Size nasıl yardımcı olabilirim?"
121
-
122
- elif "teşekkür" in msg or "sağol" in msg:
123
- return "🤖 Rica ederim! Başka bir konuda yardıma ihtiyacınız varsa sormaktan çekinmeyin."
124
-
125
- elif "?" in message:
126
- # Soru tespiti
127
- if "ne" in msg:
128
- return "🤖 Bu sorunuz üzerine düşünüyorum... Belki şöyle açıklayabilirim..."
129
- elif "nasıl" in msg:
130
- return "🤖 Bunu nasıl yapabileceğiniz konusunda size rehberlik edebilirim..."
131
- elif "neden" in msg:
132
- return "🤖 Bunun nedeni üzerine düşünelim... Muhtemelen..."
133
-
134
- elif len(message) > 100:
135
- return "🤖 Detaylı bir mesaj göndermişsiniz. Bunu analiz ediyorum ve size en iyi şekilde yardımcı olmaya çalışıyorum..."
136
 
137
- elif any(word in msg for word in ["yardım", "help", "destek"]):
138
- return "🤖 Size yardımcı olmak için buradayım! Lütfen sorunuzu daha detaylı açıklayın."
139
-
140
- elif any(word in msg for word in ["ai", "yapay zeka", "robot"]):
141
- return "🤖 Evet, ben bir yapay zeka asistanıyım! İnsanlara yardımcı olmak için programlandım."
142
-
143
- # Varsayılan akıllı yanıt
144
- responses = [
145
- f"🤖 '{message}' hakkında düşünüyorum... Size bu konuda nasıl yardımcı olabilirim?",
146
- f"🤖 İlginç bir konu! {message} hakkında size rehberlik edebilirim.",
147
- f"🤖 Anladım. {message} konusunda size nasıl destek olabileceğimi düşünüyorum.",
148
- f"🤖 Bu konuyu ele alalım. {message} hakkında size yardımcı olmaya çalışacağım."
149
- ]
150
-
151
- return random.choice(responses)
152
 
153
  # =============================================================================
154
- # ENDPOINTS
155
  # =============================================================================
156
- ai = RealAIGenerator()
157
-
158
  @app.get("/")
159
  async def root():
160
  return {
161
  "service": "ZenkaMind AI",
162
- "version": "3.0.0",
163
- "ai_mode": "real" if HF_TOKEN else "smart_fallback",
164
- "status": "running",
165
- "daily_limit": DAILY_LIMIT
166
  }
167
 
168
  @app.get("/health")
169
  async def health():
170
- db = load_db()
171
  return {
172
- "status": "healthy",
173
- "timestamp": datetime.now().isoformat(),
174
  "ai_available": bool(HF_TOKEN),
175
- "users": len(db)
176
  }
177
 
178
  @app.post("/api/chat")
@@ -182,63 +120,52 @@ async def chat(request: Request):
182
  email = data.get("email", "").strip().lower()
183
  message = data.get("message", "").strip()
184
 
185
- # Validasyon
186
  if not email or "@" not in email:
187
- return JSONResponse(400, {"error": "Geçerli email gerekli"})
188
 
189
  if not message:
190
- return JSONResponse(400, {"error": "Mesaj boş olamaz"})
191
 
192
- # Veritabanı
193
  db = load_db()
194
 
195
  if email not in db:
196
  db[email] = {
197
- "daily_count": 0,
198
- "total_messages": 0,
199
- "created": datetime.now().isoformat(),
200
  "last_reset": date.today().isoformat()
201
  }
202
 
203
  user = db[email]
204
 
205
- # Günlük reset
206
- today = date.today().isoformat()
207
- if user["last_reset"] != today:
208
- user["daily_count"] = 0
209
- user["last_reset"] = today
210
 
211
- # Limit kontrol
212
- if user["daily_count"] >= DAILY_LIMIT:
213
- return JSONResponse(429, {
214
- "response": "🚫 Günlük limit doldu. Yarın tekrar deneyin.",
215
- "status": "limit_exceeded"
216
- })
217
 
218
- # AI yanıtı al
219
- ai_response = ai.generate_response(message)
220
 
221
- # Mesaj say
222
- user["daily_count"] += 1
223
- user["total_messages"] += 1
 
 
224
 
225
- # Kaydet
 
 
226
  save_db(db)
227
 
228
- # Kalan
229
- remaining = DAILY_LIMIT - user["daily_count"]
230
-
231
- # Yanıt
232
  return {
233
  "response": ai_response,
234
- "status": "success",
235
- "remaining": remaining,
236
- "ai_mode": "real" if HF_TOKEN else "smart",
237
- "user": {
238
- "email": email,
239
- "messages_today": user["daily_count"],
240
- "total_messages": user["total_messages"]
241
- }
242
  }
243
 
244
  except Exception as e:
@@ -247,10 +174,10 @@ async def chat(request: Request):
247
  @app.get("/api/stats")
248
  async def stats():
249
  db = load_db()
250
- total = sum(u.get("total_messages", 0) for u in db.values())
251
  return {
252
  "users": len(db),
253
- "total_messages": total,
254
- "ai_mode": "real" if HF_TOKEN else "smart",
255
- "daily_limit": DAILY_LIMIT
256
  }
 
3
  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
 
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
 
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
 
45
 
46
  def save_db(data):
47
  try:
48
+ with open(DB_PATH, "w") as f:
49
+ json.dump(data, f, indent=2)
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")
 
120
  email = data.get("email", "").strip().lower()
121
  message = data.get("message", "").strip()
122
 
 
123
  if not email or "@" not in email:
124
+ return JSONResponse(400, {"error": "Email required"})
125
 
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:
133
  db[email] = {
134
+ "count": 0,
135
+ "total": 0,
 
136
  "last_reset": date.today().isoformat()
137
  }
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:
 
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
  }