Zenkad commited on
Commit
c4facf3
·
verified ·
1 Parent(s): 0a411fa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -74
app.py CHANGED
@@ -1,107 +1,86 @@
1
  from fastapi import FastAPI, Request
2
  from fastapi.responses import JSONResponse
3
  from fastapi.middleware.cors import CORSMiddleware
4
- import requests
5
  import os
6
- from datetime import date
7
 
8
- # ==============================
9
  # CONFIG
10
- # ==============================
11
- HF_MODEL = "Qwen/Qwen2.5-1.5B-Instruct"
12
  HF_API_URL = f"https://api-inference.huggingface.co/models/{HF_MODEL}"
13
  HF_TOKEN = os.getenv("HF_TOKEN")
14
 
15
- FREE_DAILY_LIMIT = 30
16
-
17
- # ==============================
18
- # RAM USER DB
19
- # ==============================
20
- USERS = {}
21
-
22
- def get_user(email: str):
23
- today = date.today().isoformat()
24
- if email not in USERS:
25
- USERS[email] = {"count": 0, "date": today}
26
- if USERS[email]["date"] != today:
27
- USERS[email]["count"] = 0
28
- USERS[email]["date"] = today
29
- return USERS[email]
30
-
31
- # ==============================
32
- # AI CALL
33
- # ==============================
34
- def ask_ai(message: str):
 
 
 
 
 
 
 
35
  prompt = f"""
36
- Sen ZenkaMind'sin.
37
  Sadece Türkçe konuş.
38
- Kısa, net ve insan gibi cevap ver.
39
 
40
  Kullanıcı: {message}
41
  ZenkaMind:
42
  """
 
43
  try:
44
- res = requests.post(
45
  HF_API_URL,
46
  headers={"Authorization": f"Bearer {HF_TOKEN}"},
47
  json={
48
  "inputs": prompt,
49
  "parameters": {
50
  "max_new_tokens": 200,
51
- "temperature": 0.7,
52
  "top_p": 0.9,
53
  "return_full_text": False
54
  }
55
  },
56
- timeout=60
57
  )
58
 
59
- if res.status_code == 503:
60
- return "⏳ Model yükleniyor, 10 saniye sonra tekrar dene."
61
 
62
- data = res.json()
63
- if isinstance(data, list) and "generated_text" in data[0]:
64
- return data[0]["generated_text"].strip()
65
 
66
- return "⚠️ Yanıt alınamadı."
 
 
 
 
 
 
67
 
68
- except Exception as e:
69
- print(e)
70
- return "❌ Sunucu hatası."
71
-
72
- # ==============================
73
- # FASTAPI
74
- # ==============================
75
- app = FastAPI()
76
 
77
- app.add_middleware(
78
- CORSMiddleware,
79
- allow_origins=["*"],
80
- allow_methods=["*"],
81
- allow_headers=["*"],
82
- )
83
-
84
- @app.get("/")
85
- def root():
86
- return {"status": "ZenkaMind API çalışıyor"}
87
 
88
- @app.post("/api/chat")
89
- async def chat(req: Request):
90
- data = await req.json()
91
- email = data.get("email", "").lower()
92
- message = data.get("message", "").strip()
93
-
94
- if not email or "@" not in email:
95
- return JSONResponse(status_code=400, content={"response": "Geçerli email gerekli."})
96
-
97
- if not message:
98
- return JSONResponse(status_code=400, content={"response": "Mesaj boş olamaz."})
99
-
100
- user = get_user(email)
101
- if user["count"] >= FREE_DAILY_LIMIT:
102
- return {"response": "Günlük limit doldu."}
103
-
104
- answer = ask_ai(message)
105
- user["count"] += 1
106
-
107
- return {"response": answer}
 
1
  from fastapi import FastAPI, Request
2
  from fastapi.responses import JSONResponse
3
  from fastapi.middleware.cors import CORSMiddleware
 
4
  import os
5
+ import requests
6
 
7
+ # =========================
8
  # CONFIG
9
+ # =========================
10
+ HF_MODEL = "tiiuae/falcon-1b-instruct"
11
  HF_API_URL = f"https://api-inference.huggingface.co/models/{HF_MODEL}"
12
  HF_TOKEN = os.getenv("HF_TOKEN")
13
 
14
+ # =========================
15
+ # FASTAPI
16
+ # =========================
17
+ app = FastAPI(title="ZenkaMind API")
18
+
19
+ app.add_middleware(
20
+ CORSMiddleware,
21
+ allow_origins=["*"],
22
+ allow_methods=["*"],
23
+ allow_headers=["*"],
24
+ )
25
+
26
+ @app.get("/")
27
+ def root():
28
+ return {"status": "ZenkaMind API çalışıyor"}
29
+
30
+ @app.post("/api/chat")
31
+ async def chat(req: Request):
32
+ data = await req.json()
33
+ message = data.get("message", "").strip()
34
+
35
+ if not message:
36
+ return JSONResponse(status_code=400, content={"response": "Mesaj boş olamaz."})
37
+
38
+ if not HF_TOKEN:
39
+ return {"response": "⚠️ HF_TOKEN tanımlı değil."}
40
+
41
  prompt = f"""
42
+ Sen ZenkaMindsin.
43
  Sadece Türkçe konuş.
44
+ Net ve kısa cevap ver.
45
 
46
  Kullanıcı: {message}
47
  ZenkaMind:
48
  """
49
+
50
  try:
51
+ r = requests.post(
52
  HF_API_URL,
53
  headers={"Authorization": f"Bearer {HF_TOKEN}"},
54
  json={
55
  "inputs": prompt,
56
  "parameters": {
57
  "max_new_tokens": 200,
58
+ "temperature": 0.6,
59
  "top_p": 0.9,
60
  "return_full_text": False
61
  }
62
  },
63
+ timeout=120
64
  )
65
 
66
+ if r.status_code == 503:
67
+ return {"response": "⏳ Model yükleniyor, 30 saniye sonra tekrar dene."}
68
 
69
+ data = r.json()
 
 
70
 
71
+ # 🔥 HF RESPONSE FIX
72
+ if isinstance(data, list) and len(data) > 0:
73
+ text = data[0].get("generated_text", "")
74
+ elif isinstance(data, dict):
75
+ text = data.get("generated_text", "")
76
+ else:
77
+ text = ""
78
 
79
+ if not text.strip():
80
+ return {"response": "⚠️ Model cevap üretmedi. Tekrar dene."}
 
 
 
 
 
 
81
 
82
+ return {"response": text.strip()}
 
 
 
 
 
 
 
 
 
83
 
84
+ except Exception as e:
85
+ print("HATA:", e)
86
+ return {"response": "❌ Sunucu hatası oluştu."}