Zenkad commited on
Commit
52a57c3
·
verified ·
1 Parent(s): 0315574

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -21
app.py CHANGED
@@ -3,7 +3,7 @@ import time
3
  from typing import List, Optional, Dict, Any
4
  import re
5
 
6
- from fastapi import FastAPI
7
  from fastapi.middleware.cors import CORSMiddleware
8
  from fastapi.responses import JSONResponse
9
  from pydantic import BaseModel
@@ -13,18 +13,19 @@ from huggingface_hub import InferenceClient
13
  # MODEL
14
  # ===============================
15
  MODEL_ID = "Qwen/Qwen2.5-0.5B-Instruct"
16
- HF_TOKEN = os.getenv("HF_TOKEN")
17
 
18
  client = InferenceClient(model=MODEL_ID, token=HF_TOKEN)
19
 
20
  # ===============================
21
  # APP
22
  # ===============================
23
- app = FastAPI()
24
 
25
  app.add_middleware(
26
  CORSMiddleware,
27
  allow_origins=["*"],
 
28
  allow_methods=["*"],
29
  allow_headers=["*"],
30
  )
@@ -149,7 +150,6 @@ def enhance_freelance_response(message: str, response: str) -> str:
149
  """Freelance modu için cevabı geliştir"""
150
  message_lower = message.lower()
151
 
152
- # Özel freelance konularına göre ek tavsiyeler
153
  enhancements = []
154
 
155
  if any(word in message_lower for word in ["fiyat", "ücret", "price", "fee", "ne kadar"]):
@@ -182,18 +182,25 @@ def enhance_freelance_response(message: str, response: str) -> str:
182
  # ENDPOINTLER
183
  # ===============================
184
  @app.get("/")
185
- def root():
186
  return {
187
  "status": "ok",
188
  "service": "ZenkaMind API",
189
  "model": MODEL_ID,
190
  "free_limit": FREE_MESSAGE_LIMIT,
191
  "modes": list(PROMPTS.keys()),
192
- "version": "2.0"
 
 
193
  }
194
 
 
 
 
 
 
195
  @app.get("/modes")
196
- def get_modes():
197
  """Mevcut modları listele"""
198
  modes_info = {
199
  "agir_abi": "Ağır abi tavrı - Hayat dersi veren, otoriter",
@@ -205,7 +212,7 @@ def get_modes():
205
  return {"modes": modes_info}
206
 
207
  @app.post("/api/chat")
208
- def chat(body: ChatRequest):
209
  user_key = body.user_id or "anon"
210
  count = usage_counts.get(user_key, 0)
211
 
@@ -217,7 +224,6 @@ def chat(body: ChatRequest):
217
  "premium_required": True
218
  })
219
 
220
- # Mod kontrolü
221
  mode = body.mode if body.mode in PROMPTS else "agir_abi"
222
  system_prompt = PROMPTS[mode]
223
 
@@ -225,7 +231,6 @@ def chat(body: ChatRequest):
225
  {"role": "system", "content": system_prompt}
226
  ]
227
 
228
- # History işleme
229
  for pair in body.history or []:
230
  if len(pair) == 2:
231
  messages.append({"role": "user", "content": str(pair[0])})
@@ -244,7 +249,6 @@ def chat(body: ChatRequest):
244
  answer = result.choices[0].message.content.strip()
245
  answer = clean_response(answer)
246
 
247
- # Freelance modu için özel geliştirme
248
  if mode == "freelance":
249
  answer = enhance_freelance_response(body.message, answer)
250
 
@@ -262,7 +266,6 @@ def chat(body: ChatRequest):
262
 
263
  except Exception as e:
264
  error_msg = str(e)
265
- # Basit hata mesajı
266
  if "rate limit" in error_msg.lower():
267
  fallback_response = "Şu anda yoğunluk var. Lütfen 1 dakika sonra tekrar deneyin."
268
  elif "token" in error_msg.lower():
@@ -279,7 +282,7 @@ def chat(body: ChatRequest):
279
  }
280
 
281
  @app.get("/api/usage/{user_id}")
282
- def get_usage(user_id: str):
283
  """Kullanım bilgilerini getir"""
284
  count = usage_counts.get(user_id, 0)
285
  remaining = FREE_MESSAGE_LIMIT - count
@@ -293,7 +296,7 @@ def get_usage(user_id: str):
293
  }
294
 
295
  @app.get("/api/stats")
296
- def get_stats():
297
  """Genel istatistikler"""
298
  total_users = len(usage_counts)
299
  total_messages = sum(usage_counts.values())
@@ -306,7 +309,7 @@ def get_stats():
306
  }
307
 
308
  @app.post("/api/reset/{user_id}")
309
- def reset_usage(user_id: str):
310
  """Kullanıcı kullanımını sıfırla"""
311
  if user_id in usage_counts:
312
  usage_counts[user_id] = 0
@@ -317,7 +320,7 @@ def reset_usage(user_id: str):
317
  # FREELANCE ÖZEL ENDPOINTLER
318
  # ===============================
319
  @app.get("/freelance/tips")
320
- def freelance_tips():
321
  """Freelance için hızlı ipuçları"""
322
  tips = [
323
  "1. Her proje için net sözleşme imzala",
@@ -334,7 +337,7 @@ def freelance_tips():
334
  return {"tips": tips}
335
 
336
  @app.get("/freelance/checklist")
337
- def freelance_checklist():
338
  """Yeni proje başlangıç checklist"""
339
  checklist = {
340
  "öncesi": [
@@ -360,7 +363,7 @@ def freelance_checklist():
360
  }
361
  return checklist
362
 
363
- if __name__ == "__main__":
364
- import uvicorn
365
- # DÜZELTME: reload parametresini kaldır
366
- uvicorn.run("app:app", host="0.0.0.0", port=8000)
 
3
  from typing import List, Optional, Dict, Any
4
  import re
5
 
6
+ from fastapi import FastAPI, Request
7
  from fastapi.middleware.cors import CORSMiddleware
8
  from fastapi.responses import JSONResponse
9
  from pydantic import BaseModel
 
13
  # MODEL
14
  # ===============================
15
  MODEL_ID = "Qwen/Qwen2.5-0.5B-Instruct"
16
+ HF_TOKEN = os.getenv("HF_TOKEN", os.getenv("HUGGINGFACE_TOKEN"))
17
 
18
  client = InferenceClient(model=MODEL_ID, token=HF_TOKEN)
19
 
20
  # ===============================
21
  # APP
22
  # ===============================
23
+ app = FastAPI(title="ZenkaMind API", version="2.0")
24
 
25
  app.add_middleware(
26
  CORSMiddleware,
27
  allow_origins=["*"],
28
+ allow_credentials=True,
29
  allow_methods=["*"],
30
  allow_headers=["*"],
31
  )
 
150
  """Freelance modu için cevabı geliştir"""
151
  message_lower = message.lower()
152
 
 
153
  enhancements = []
154
 
155
  if any(word in message_lower for word in ["fiyat", "ücret", "price", "fee", "ne kadar"]):
 
182
  # ENDPOINTLER
183
  # ===============================
184
  @app.get("/")
185
+ async def root():
186
  return {
187
  "status": "ok",
188
  "service": "ZenkaMind API",
189
  "model": MODEL_ID,
190
  "free_limit": FREE_MESSAGE_LIMIT,
191
  "modes": list(PROMPTS.keys()),
192
+ "version": "2.0",
193
+ "docs": "/docs",
194
+ "environment": os.getenv("SPACE_ID", "development")
195
  }
196
 
197
+ @app.get("/health")
198
+ async def health_check():
199
+ """Sağlık kontrol endpoint'i"""
200
+ return {"status": "healthy", "timestamp": time.time()}
201
+
202
  @app.get("/modes")
203
+ async def get_modes():
204
  """Mevcut modları listele"""
205
  modes_info = {
206
  "agir_abi": "Ağır abi tavrı - Hayat dersi veren, otoriter",
 
212
  return {"modes": modes_info}
213
 
214
  @app.post("/api/chat")
215
+ async def chat(body: ChatRequest):
216
  user_key = body.user_id or "anon"
217
  count = usage_counts.get(user_key, 0)
218
 
 
224
  "premium_required": True
225
  })
226
 
 
227
  mode = body.mode if body.mode in PROMPTS else "agir_abi"
228
  system_prompt = PROMPTS[mode]
229
 
 
231
  {"role": "system", "content": system_prompt}
232
  ]
233
 
 
234
  for pair in body.history or []:
235
  if len(pair) == 2:
236
  messages.append({"role": "user", "content": str(pair[0])})
 
249
  answer = result.choices[0].message.content.strip()
250
  answer = clean_response(answer)
251
 
 
252
  if mode == "freelance":
253
  answer = enhance_freelance_response(body.message, answer)
254
 
 
266
 
267
  except Exception as e:
268
  error_msg = str(e)
 
269
  if "rate limit" in error_msg.lower():
270
  fallback_response = "Şu anda yoğunluk var. Lütfen 1 dakika sonra tekrar deneyin."
271
  elif "token" in error_msg.lower():
 
282
  }
283
 
284
  @app.get("/api/usage/{user_id}")
285
+ async def get_usage(user_id: str):
286
  """Kullanım bilgilerini getir"""
287
  count = usage_counts.get(user_id, 0)
288
  remaining = FREE_MESSAGE_LIMIT - count
 
296
  }
297
 
298
  @app.get("/api/stats")
299
+ async def get_stats():
300
  """Genel istatistikler"""
301
  total_users = len(usage_counts)
302
  total_messages = sum(usage_counts.values())
 
309
  }
310
 
311
  @app.post("/api/reset/{user_id}")
312
+ async def reset_usage(user_id: str):
313
  """Kullanıcı kullanımını sıfırla"""
314
  if user_id in usage_counts:
315
  usage_counts[user_id] = 0
 
320
  # FREELANCE ÖZEL ENDPOINTLER
321
  # ===============================
322
  @app.get("/freelance/tips")
323
+ async def freelance_tips():
324
  """Freelance için hızlı ipuçları"""
325
  tips = [
326
  "1. Her proje için net sözleşme imzala",
 
337
  return {"tips": tips}
338
 
339
  @app.get("/freelance/checklist")
340
+ async def freelance_checklist():
341
  """Yeni proje başlangıç checklist"""
342
  checklist = {
343
  "öncesi": [
 
363
  }
364
  return checklist
365
 
366
+ # ===============================
367
+ # HUGGING FACE SPACES İÇİN ÖZEL AYAR
368
+ # ===============================
369
+ # Bu kısmı olduğu gibi bırakın, HF Spaces bunu otomatik yönetecek