Zenkad commited on
Commit
3912897
·
verified ·
1 Parent(s): ffbdfb4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +257 -0
app.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ from datetime import datetime, date
4
+ from fastapi import FastAPI, Request
5
+ from fastapi.responses import JSONResponse, HTMLResponse
6
+ from fastapi.middleware.cors import CORSMiddleware
7
+
8
+ # ==================== AYARLAR ====================
9
+ app = FastAPI(title="ZenkaAI")
10
+
11
+ app.add_middleware(
12
+ CORSMiddleware,
13
+ allow_origins=["*"],
14
+ allow_methods=["*"],
15
+ allow_headers=["*"],
16
+ )
17
+
18
+ HF_TOKEN = os.getenv("HF_TOKEN", "")
19
+ MODEL = "microsoft/DialoGPT-small"
20
+ API_URL = f"https://api-inference.huggingface.co/models/{MODEL}"
21
+
22
+ users_db = {}
23
+ LIMIT = 30
24
+ SHOPIER = "https://shopier.com/42153760"
25
+
26
+ # ==================== FONKSİYONLAR ====================
27
+ def get_user(email):
28
+ email = email.lower().strip()
29
+ today = date.today().isoformat()
30
+
31
+ if email not in users_db:
32
+ users_db[email] = {"count": 0, "date": today}
33
+
34
+ user = users_db[email]
35
+ if user["date"] != today:
36
+ user["count"] = 0
37
+ user["date"] = today
38
+
39
+ return user
40
+
41
+ def get_ai_response(message):
42
+ if not HF_TOKEN:
43
+ return "🤖 ZenkaAI: Hoşgeldiniz! Token ayarlanmamış."
44
+
45
+ try:
46
+ response = requests.post(
47
+ API_URL,
48
+ headers={"Authorization": f"Bearer {HF_TOKEN}"},
49
+ json={"inputs": f"Soru: {message}\nCevap:"},
50
+ timeout=15
51
+ )
52
+
53
+ if response.status_code == 200:
54
+ result = response.json()
55
+ if isinstance(result, list) and result:
56
+ text = result[0].get('generated_text', '')
57
+ if text:
58
+ return f"🤖 {text.split('Cevap:')[-1].strip()}"
59
+
60
+ return "🤖 Size nasıl yardımcı olabilirim?"
61
+
62
+ except:
63
+ return "🤖 Teknik bir sorun oluştu."
64
+
65
+ # ==================== ROTALAR ====================
66
+ @app.get("/")
67
+ async def home():
68
+ html = """
69
+ <!DOCTYPE html>
70
+ <html>
71
+ <head>
72
+ <meta charset="UTF-8">
73
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
74
+ <title>ZenkaAI - Türkçe AI</title>
75
+ <style>
76
+ body {
77
+ font-family: Arial;
78
+ margin: 0;
79
+ padding: 20px;
80
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
81
+ min-height: 100vh;
82
+ }
83
+ .container {
84
+ max-width: 600px;
85
+ margin: auto;
86
+ background: white;
87
+ padding: 25px;
88
+ border-radius: 15px;
89
+ box-shadow: 0 10px 30px rgba(0,0,0,0.3);
90
+ }
91
+ h1 { color: #4f46e5; text-align: center; }
92
+ .chat-box {
93
+ height: 350px;
94
+ overflow-y: auto;
95
+ border: 2px solid #e5e7eb;
96
+ border-radius: 10px;
97
+ padding: 15px;
98
+ margin: 20px 0;
99
+ background: #f9fafb;
100
+ }
101
+ .msg {
102
+ margin: 10px 0;
103
+ padding: 10px 15px;
104
+ border-radius: 10px;
105
+ max-width: 80%;
106
+ }
107
+ .user { background: #4f46e5; color: white; margin-left: auto; }
108
+ .ai { background: white; border: 1px solid #e5e7eb; }
109
+ input, textarea, button {
110
+ width: 100%;
111
+ padding: 12px;
112
+ margin: 8px 0;
113
+ border: 2px solid #ddd;
114
+ border-radius: 10px;
115
+ font-size: 16px;
116
+ box-sizing: border-box;
117
+ }
118
+ button {
119
+ background: #4f46e5;
120
+ color: white;
121
+ border: none;
122
+ font-weight: bold;
123
+ cursor: pointer;
124
+ }
125
+ .info {
126
+ text-align: center;
127
+ margin-top: 15px;
128
+ color: #666;
129
+ font-size: 14px;
130
+ }
131
+ </style>
132
+ </head>
133
+ <body>
134
+ <div class="container">
135
+ <h1>🤖 ZenkaAI</h1>
136
+ <div style="padding:10px;background:#d1fae5;border-radius:8px;text-align:center;margin:15px 0;">
137
+ ✅ Sistem Çalışıyor
138
+ </div>
139
+
140
+ <div class="chat-box" id="chatBox">
141
+ <div class="msg ai">
142
+ <strong>AI:</strong> Merhaba! Ben ZenkaAI. Size nasıl yardımcı olabilirim?
143
+ </div>
144
+ </div>
145
+
146
+ <input type="email" id="email" placeholder="Email" value="test@example.com">
147
+ <textarea id="message" placeholder="Mesajınız..." rows="3"></textarea>
148
+ <button onclick="sendMessage()">Gönder</button>
149
+
150
+ <div class="info">
151
+ <p>Günlük limit: 30 sorgu • Premium: """ + SHOPIER + """</p>
152
+ </div>
153
+ </div>
154
+
155
+ <script>
156
+ async function sendMessage() {
157
+ const email = document.getElementById('email').value;
158
+ const message = document.getElementById('message').value;
159
+
160
+ if (!email || !message) {
161
+ alert('Email ve mesaj gerekli!');
162
+ return;
163
+ }
164
+
165
+ // Kullanıcı mesajı
166
+ const chatBox = document.getElementById('chatBox');
167
+ const userMsg = document.createElement('div');
168
+ userMsg.className = 'msg user';
169
+ userMsg.innerHTML = '<strong>Siz:</strong> ' + message;
170
+ chatBox.appendChild(userMsg);
171
+
172
+ document.getElementById('message').value = '';
173
+
174
+ try {
175
+ const response = await fetch('/api/chat', {
176
+ method: 'POST',
177
+ headers: {'Content-Type': 'application/json'},
178
+ body: JSON.stringify({email, message})
179
+ });
180
+
181
+ const data = await response.json();
182
+
183
+ // AI yanıtı
184
+ const aiMsg = document.createElement('div');
185
+ aiMsg.className = 'msg ai';
186
+ aiMsg.innerHTML = '<strong>AI:</strong> ' + data.response;
187
+ chatBox.appendChild(aiMsg);
188
+
189
+ chatBox.scrollTop = chatBox.scrollHeight;
190
+
191
+ } catch (error) {
192
+ alert('Hata: ' + error.message);
193
+ }
194
+ }
195
+
196
+ // Enter tuşu
197
+ document.getElementById('message').addEventListener('keypress', function(e) {
198
+ if (e.key === 'Enter' && !e.shiftKey) {
199
+ e.preventDefault();
200
+ sendMessage();
201
+ }
202
+ });
203
+ </script>
204
+ </body>
205
+ </html>
206
+ """
207
+ return HTMLResponse(content=html)
208
+
209
+ @app.get("/health")
210
+ async def health():
211
+ return {
212
+ "status": "ok",
213
+ "service": "ZenkaAI",
214
+ "time": datetime.now().isoformat(),
215
+ "token": "var" if HF_TOKEN else "yok"
216
+ }
217
+
218
+ @app.post("/api/chat")
219
+ async def chat(request: Request):
220
+ try:
221
+ data = await request.json()
222
+ except:
223
+ return JSONResponse({"error": "Geçersiz JSON"}, status_code=400)
224
+
225
+ email = data.get("email", "").strip()
226
+ message = data.get("message", "").strip()
227
+
228
+ if not email or "@" not in email:
229
+ return JSONResponse({"error": "Geçerli email gerekli"}, status_code=400)
230
+
231
+ if not message:
232
+ return JSONResponse({"error": "Mesaj boş olamaz"}, status_code=400)
233
+
234
+ user = get_user(email)
235
+
236
+ if user["count"] >= LIMIT:
237
+ return JSONResponse({
238
+ "response": f"Günlük limit ({LIMIT}) doldu. Premium: {SHOPIER}",
239
+ "status": "limit"
240
+ }, status_code=429)
241
+
242
+ response = get_ai_response(message)
243
+ user["count"] += 1
244
+
245
+ return {
246
+ "response": response,
247
+ "status": "success",
248
+ "remaining": LIMIT - user["count"],
249
+ "used": user["count"]
250
+ }
251
+
252
+ # ==================== ÇALIŞTIRMA ====================
253
+ if __name__ == "__main__":
254
+ import uvicorn
255
+ print("🚀 ZenkaAI Başlatılıyor...")
256
+ print(f"🔑 Token: {'✅ Var' if HF_TOKEN else '⚠️ Yok'}")
257
+ uvicorn.run(app, host="0.0.0.0", port=7860)