HilmanBey commited on
Commit
89ceaa4
·
verified ·
1 Parent(s): 243ac06

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +130 -19
main.py CHANGED
@@ -1,5 +1,7 @@
1
  import os
2
  import requests
 
 
3
  from fastapi import FastAPI, Header, HTTPException
4
  from pydantic import BaseModel
5
 
@@ -9,21 +11,65 @@ MY_SECRET_KEY = os.getenv("MY_SECRET_KEY", "hilman-secret-2026")
9
  OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
10
  ANTIGRAVITY_API_KEY = os.getenv("ANTIGRAVITY_API_KEY")
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  class ChatRequest(BaseModel):
13
  provider: str = "antigravity"
14
  model: str = "gemini-2.0-flash"
15
  messages: list
16
 
17
- @app.get("/")
18
  def status():
19
  return {"status": "HilmanAI Core Online", "system": "7/24 Active"}
20
 
21
- @app.post("/v1/chat/completions")
22
- def chat_proxy(req: ChatRequest, authorization: str = Header(None)):
23
- if authorization != f"Bearer {MY_SECRET_KEY}":
24
- raise HTTPException(status_code=401, detail="Yetkisiz erişim!")
25
-
26
- compressed_messages = req.messages[-4:] if len(req.messages) > 4 else req.messages
27
 
28
  system_instruction = {
29
  "role": "system",
@@ -38,7 +84,7 @@ def chat_proxy(req: ChatRequest, authorization: str = Header(None)):
38
 
39
  full_messages = [system_instruction] + compressed_messages
40
 
41
- # --- 1. ANTIGRAVITY DENEMESİ (MAX 4 SANİYE BEKLE) ---
42
  if ANTIGRAVITY_API_KEY:
43
  ag_headers = {
44
  "Authorization": f"Bearer {ANTIGRAVITY_API_KEY.strip()}",
@@ -54,13 +100,12 @@ def chat_proxy(req: ChatRequest, authorization: str = Header(None)):
54
  ag_res = requests.post("https://api.antigravity.dev/v1/chat/completions", json=ag_payload, headers=ag_headers, timeout=4)
55
  if ag_res.status_code == 200:
56
  print("[BAŞARILI]: Antigravity yanıt verdi!")
57
- return ag_res.json()
58
- else:
59
- print(f"[ANTIGRAVITY ATLANDI]: HTTP {ag_res.status_code}")
60
  except Exception as e:
61
- print(f"[ANTIGRAVITY YANIT VERMEDİ - GEÇİLİYOR]: {e}")
62
 
63
- # --- 2. OPENROUTER DÜŞME ALANI (IŞIK HIZINDA YEDEK) ---
64
  if OPENROUTER_API_KEY:
65
  or_headers = {
66
  "Authorization": f"Bearer {OPENROUTER_API_KEY.strip()}",
@@ -85,11 +130,77 @@ def chat_proxy(req: ChatRequest, authorization: str = Header(None)):
85
  )
86
  if or_res.status_code == 200:
87
  print(f"[BAŞARILI]: OpenRouter ({m}) yanıt verdi!")
88
- return or_res.json()
89
- else:
90
- print(f"[OPENROUTER MODEL HATASI]: {m} -> {or_res.status_code}")
91
- except Exception as e:
92
- print(f"[OPENROUTER MODEL ZAMANAŞIMI]: {m} -> {e}")
93
  continue
94
 
95
- raise HTTPException(status_code=503, detail="Tüm yapay zeka servisleri meşgul veya ulaşılamıyor.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import requests
3
+ import sqlite3
4
+ import gradio as gr
5
  from fastapi import FastAPI, Header, HTTPException
6
  from pydantic import BaseModel
7
 
 
11
  OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
12
  ANTIGRAVITY_API_KEY = os.getenv("ANTIGRAVITY_API_KEY")
13
 
14
+ # --- VERİTABANI VE KALICI HAFIZA ---
15
+ DB_PATH = "hilman_space_memory.db"
16
+
17
+ def init_db():
18
+ try:
19
+ conn = sqlite3.connect(DB_PATH)
20
+ cursor = conn.cursor()
21
+ cursor.execute("""
22
+ CREATE TABLE IF NOT EXISTS messages (
23
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
24
+ role TEXT,
25
+ content TEXT,
26
+ timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
27
+ )
28
+ """)
29
+ conn.commit()
30
+ conn.close()
31
+ except Exception as e:
32
+ print(f"DB Başlatma Hatası: {e}")
33
+
34
+ init_db()
35
+
36
+ def save_message(role, content):
37
+ try:
38
+ conn = sqlite3.connect(DB_PATH)
39
+ cursor = conn.cursor()
40
+ cursor.execute("INSERT INTO messages (role, content) VALUES (?, ?)", (role, content))
41
+ conn.commit()
42
+ conn.close()
43
+ except Exception as e:
44
+ print(f"DB Kayıt Hatası: {e}")
45
+
46
+ def get_chat_history():
47
+ try:
48
+ conn = sqlite3.connect(DB_PATH)
49
+ cursor = conn.cursor()
50
+ cursor.execute("SELECT role, content FROM messages ORDER BY id ASC")
51
+ rows = cursor.fetchall()
52
+ conn.close()
53
+
54
+ history = []
55
+ for role, content in rows:
56
+ history.append({"role": role, "content": content})
57
+ return history
58
+ except Exception:
59
+ return []
60
+
61
  class ChatRequest(BaseModel):
62
  provider: str = "antigravity"
63
  model: str = "gemini-2.0-flash"
64
  messages: list
65
 
66
+ @app.get("/status")
67
  def status():
68
  return {"status": "HilmanAI Core Online", "system": "7/24 Active"}
69
 
70
+ # --- ORTAK YAPAY ZEKA ÇALIŞTIRICI (API & Web Arayüzü İçin) ---
71
+ def call_ai_backend(messages_list):
72
+ compressed_messages = messages_list[-4:] if len(messages_list) > 4 else messages_list
 
 
 
73
 
74
  system_instruction = {
75
  "role": "system",
 
84
 
85
  full_messages = [system_instruction] + compressed_messages
86
 
87
+ # --- 1. ANTIGRAVITY DENEMESİ ---
88
  if ANTIGRAVITY_API_KEY:
89
  ag_headers = {
90
  "Authorization": f"Bearer {ANTIGRAVITY_API_KEY.strip()}",
 
100
  ag_res = requests.post("https://api.antigravity.dev/v1/chat/completions", json=ag_payload, headers=ag_headers, timeout=4)
101
  if ag_res.status_code == 200:
102
  print("[BAŞARILI]: Antigravity yanıt verdi!")
103
+ data = ag_res.json()
104
+ return data["choices"][0]["message"]["content"]
 
105
  except Exception as e:
106
+ print(f"[ANTIGRAVITY YANIT VERMEDİ]: {e}")
107
 
108
+ # --- 2. OPENROUTER YEDEK ---
109
  if OPENROUTER_API_KEY:
110
  or_headers = {
111
  "Authorization": f"Bearer {OPENROUTER_API_KEY.strip()}",
 
130
  )
131
  if or_res.status_code == 200:
132
  print(f"[BAŞARILI]: OpenRouter ({m}) yanıt verdi!")
133
+ data = or_res.json()
134
+ return data["choices"][0]["message"]["content"]
135
+ except Exception:
 
 
136
  continue
137
 
138
+ return "Tüm yapay zeka servisleri şu an meşgul, Hilman."
139
+
140
+ # --- API ENDPOINT ---
141
+ @app.post("/v1/chat/completions")
142
+ def chat_proxy(req: ChatRequest, authorization: str = Header(None)):
143
+ if authorization != f"Bearer {MY_SECRET_KEY}":
144
+ raise HTTPException(status_code=401, detail="Yetkisiz erişim!")
145
+
146
+ # Gelen mesajları veritabanına kaydet
147
+ for m in req.messages:
148
+ if isinstance(m, dict) and "role" in m and "content" in m:
149
+ save_message(m["role"], m["content"])
150
+
151
+ # Yapay zekadan yanıt al
152
+ ai_response_text = call_ai_backend(req.messages)
153
+
154
+ # Asistan yanıtını kaydet
155
+ save_message("assistant", ai_response_text)
156
+
157
+ # OpenAI formatında yanıt dön
158
+ return {
159
+ "choices": [
160
+ {
161
+ "message": {
162
+ "role": "assistant",
163
+ "content": ai_response_text
164
+ }
165
+ }
166
+ ]
167
+ }
168
+
169
+ # --- GRADIO WEB ARAYÜZÜ ---
170
+ def gradio_predict(message, history):
171
+ if not message.strip():
172
+ return ""
173
+
174
+ # Kullanıcı mesajını kaydet
175
+ save_message("user", message)
176
+
177
+ # Geçmişi veritabanından al ve yapay zekaya gönder
178
+ current_history = get_chat_history()
179
+ response_text = call_ai_backend(current_history)
180
+
181
+ # Asistan yanıtını kaydet
182
+ save_message("assistant", response_text)
183
+
184
+ return response_text
185
+
186
+ with gr.Blocks(theme=gr.themes.Dark()) as demo:
187
+ gr.Markdown("# ⚡ HILMAN AI - Cloud Jarvis Core")
188
+ gr.Markdown("7/24 Aktif, SQLite Veritabanı Destekli Güvenli Bulut Paneli")
189
+
190
+ gr.ChatInterface(
191
+ fn=gradio_predict,
192
+ title="",
193
+ description="HilmanAI Güvenli Web Arayüzü",
194
+ textbox=gr.Textbox(placeholder="Komutunuzu girin Hilman...", container=False, scale=7),
195
+ submit_btn="GÖNDER",
196
+ chatbot=gr.Chatbot(height=550, value=get_chat_history(), type="messages")
197
+ )
198
+
199
+ # Gradio Arayüzünü FastAPI'ye şifre korumasıyla (Giriş Ekranı) bağla
200
+ app = gr.mount_gradio_app(
201
+ app,
202
+ demo,
203
+ path="/",
204
+ auth=("patron", "hilman2026"),
205
+ auth_message="HILMAN AI Güvenli Giriş Paneli - Kimlik Doğrulayın"
206
+ )