Spaces:
Sleeping
Sleeping
| import os | |
| import requests | |
| import sqlite3 | |
| from fastapi import FastAPI, Header, HTTPException, Request | |
| from fastapi.responses import JSONResponse | |
| from pydantic import BaseModel | |
| from duckduckgo_search import DDGS | |
| app = FastAPI(title="HilmanAI Real Cloud Proxy Gateway") | |
| # --- ÇEVRE DEĞİŞKENLERİ (Hugging Face Secrets'tan çekilir) --- | |
| MY_SECRET_KEY = os.getenv("MY_SECRET_KEY", "sk-hilman-proxy-2026") | |
| OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY") | |
| ANTIGRAVITY_API_KEY = os.getenv("ANTIGRAVITY_API_KEY") | |
| # --- VERİTABANI (İstek Logları ve Hafıza) --- | |
| DB_PATH = "hilman_space_memory.db" | |
| def init_db(): | |
| try: | |
| conn = sqlite3.connect(DB_PATH) | |
| cursor = conn.cursor() | |
| cursor.execute(""" | |
| CREATE TABLE IF NOT EXISTS messages ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| role TEXT, | |
| content TEXT, | |
| timestamp DATETIME DEFAULT CURRENT_TIMESTAMP | |
| ) | |
| """) | |
| conn.commit() | |
| conn.close() | |
| except Exception as e: | |
| print(f"DB Başlatma Hatası: {e}") | |
| init_db() | |
| def save_message(role, content): | |
| try: | |
| conn = sqlite3.connect(DB_PATH) | |
| cursor = conn.cursor() | |
| cursor.execute("INSERT INTO messages (role, content) VALUES (?, ?)", (role, content)) | |
| conn.commit() | |
| conn.close() | |
| except Exception as e: | |
| print(f"DB Kayıt Hatası: {e}") | |
| # --- İNTERNET ARAMA MOTORU --- | |
| def web_search(query: str) -> str: | |
| try: | |
| print(f"[İNTERNET ARAMASI]: '{query}' aranıyor...") | |
| results_text = "" | |
| with DDGS() as ddgs: | |
| results = list(ddgs.text(query, max_results=5)) | |
| for r in results: | |
| title = r.get("title", "Başlık Yok") | |
| body = r.get("body", "Açıklama Yok") | |
| href = r.get("href", "#") | |
| results_text += f"- Ürün/Kaynak: {title}\n Özet/Detay: {body}\n Link: {href}\n\n" | |
| return results_text if results_text else "Web aramasında sonuç bulunamadı." | |
| except Exception as e: | |
| print(f"[ARAMA HATASI]: {e}") | |
| return f"Arama sırasında hata oluştu: {e}" | |
| class ChatRequest(BaseModel): | |
| model: str = "google/gemini-2.0-flash-lite-001" | |
| messages: list | |
| temperature: float = 0.2 | |
| # --- SUNUCU SAĞLIK VE DURUM KONTROLÜ --- | |
| def root(): | |
| return { | |
| "status": "online", | |
| "message": "HilmanAI Cloud Proxy is active and running 24/7, Halil.", | |
| "endpoints": { | |
| "chat_completions": "/v1/chat/completions", | |
| "status": "/server-status" | |
| } | |
| } | |
| def server_status(): | |
| return { | |
| "service": "Running", | |
| "port": 7860, | |
| "auth_enabled": True, | |
| "providers_loaded": { | |
| "openrouter": bool(OPENROUTER_API_KEY), | |
| "antigravity": bool(ANTIGRAVITY_API_KEY) | |
| } | |
| } | |
| # --- GERÇEK PROXY İSTEK YÖNLENDİRİCİSİ --- | |
| def proxy_chat_completions(req: ChatRequest, authorization: str = Header(None)): | |
| # 1. Güvenlik ve Yetkilendirme Kontrolü | |
| if not authorization or authorization != f"Bearer {MY_SECRET_KEY}": | |
| raise HTTPException(status_code=401, detail="Yetkisiz erişim! Geçersiz Secret Key.") | |
| # 2. Gelen Mesajları Veritabanına Kaydet | |
| last_user_msg = "" | |
| for m in req.messages: | |
| if isinstance(m, dict): | |
| role = m.get("role", "user") | |
| content = m.get("content", "") | |
| if role == "user": | |
| last_user_msg = content | |
| save_message(role, content) | |
| # 3. Canlı İnternet Arama Tetikleyicisi | |
| search_keywords = ["bul", "ara", "fiyat", "en ucuz", "nerede", "satın al", "karşılaştır", "incele"] | |
| search_context = "" | |
| if any(kw in last_user_msg.lower() for kw in search_keywords): | |
| search_results = web_search(last_user_msg) | |
| search_context = f"\n\n[CANLI İNTERNET ARAMA SONUÇLARI]:\n{search_results}\nYukarıdaki güncel internet verilerini kullanarak Halil'e net, fiyatlı ve detaylı bilgi sun." | |
| # Sistem Talimatı Ekleme | |
| system_instruction = { | |
| "role": "system", | |
| "content": ( | |
| "Sen HilmanAI'sın. Kullanıcıya her zaman 'Halil' diye hitap edeceksin. " | |
| "İşletim sistemi WINDOWS'tur. " | |
| "Halil internetten ürün, fiyat veya araştırma istediğinde sana sağlanan [CANLI İNTERNET ARAMA SONUÇLARI]'nı kullan." | |
| ) | |
| } | |
| full_messages = [system_instruction] + req.messages | |
| if search_context and len(full_messages) > 1: | |
| if isinstance(full_messages[-1], dict): | |
| full_messages[-1]["content"] += search_context | |
| ai_response_text = "Tüm yapay zeka servisleri şu an yanıt vermiyor." | |
| # 4. Antigravity API Üzerinden Proxy İsteği | |
| if ANTIGRAVITY_API_KEY: | |
| try: | |
| headers = { | |
| "Authorization": f"Bearer {ANTIGRAVITY_API_KEY.strip()}", | |
| "Content-Type": "application/json" | |
| } | |
| payload = { | |
| "model": "gemini-2.0-flash", | |
| "messages": full_messages, | |
| "temperature": req.temperature | |
| } | |
| res = requests.post("https://api.antigravity.dev/v1/chat/completions", json=payload, headers=headers, timeout=15) | |
| if res.status_code == 200: | |
| data = res.json() | |
| ai_response_text = data["choices"][0]["message"]["content"] | |
| save_message("assistant", ai_response_text) | |
| return res.json() | |
| except Exception as e: | |
| print(f"Antigravity Proxy Hatası: {e}") | |
| # 5. OpenRouter API Üzerinden Proxy İsteği (Yedek) | |
| if OPENROUTER_API_KEY: | |
| try: | |
| headers = { | |
| "Authorization": f"Bearer {OPENROUTER_API_KEY.strip()}", | |
| "Content-Type": "application/json", | |
| "HTTP-Referer": "https://huggingface.co", | |
| "X-Title": "HilmanAI" | |
| } | |
| fallback_models = [ | |
| req.model, | |
| "google/gemini-2.0-flash-lite-001", | |
| "meta-llama/llama-3.3-70b-instruct" | |
| ] | |
| for model_name in fallback_models: | |
| payload = { | |
| "model": model_name, | |
| "messages": full_messages, | |
| "temperature": req.temperature | |
| } | |
| res = requests.post("https://openrouter.ai/api/v1/chat/completions", json=payload, headers=headers, timeout=15) | |
| if res.status_code == 200: | |
| data = res.json() | |
| ai_response_text = data["choices"][0]["message"]["content"] | |
| save_message("assistant", ai_response_text) | |
| return res.json() | |
| except Exception as e: | |
| print(f"OpenRouter Proxy Hatası: {e}") | |
| raise HTTPException(status_code=500, detail="Hiçbir AI Sağlayıcısından yanıt alınamadı.") |