Spaces:
Sleeping
Sleeping
| import os | |
| import json | |
| import requests | |
| from flask import Flask, request, jsonify | |
| from flask_cors import CORS | |
| import firebase_admin | |
| from firebase_admin import credentials, firestore | |
| app = Flask(__name__) | |
| CORS(app) | |
| # --- FIREBASE SETUP (SECURE via SECRET) --- | |
| try: | |
| if not firebase_admin._apps: | |
| firebase_key = os.environ.get("FIREBASE_KEY") | |
| cred = credentials.Certificate(json.loads(firebase_key)) | |
| firebase_admin.initialize_app(cred) | |
| db = firestore.client() | |
| except Exception as e: | |
| print("Firebase error:", e) | |
| # --- SECRETS --- | |
| # HF_TOKEN ki ab zaroorat nahi hai, sab kuch OpenRouter se hoga | |
| OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY") | |
| TG_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN") | |
| TG_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID") | |
| # --- MODELS (Dono OpenRouter ke hain ab) --- | |
| TEXT_MODEL = "cognitivecomputations/dolphin-mixtral-8x7b" # Dolphin Uncensored | |
| VISION_MODEL = "openai/gpt-4o-mini" # Best Vision | |
| def home(): | |
| return jsonify({"status": "TS AI Secure Brain (Uncensored Mode) Running π"}) | |
| def chat(): | |
| try: | |
| is_form_data = 'multipart/form-data' in request.content_type if request.content_type else False | |
| user_message = "" | |
| image_url = None | |
| # ===== INPUT HANDLE ===== | |
| if is_form_data: | |
| user_message = request.form.get("message", "Explain this image") | |
| if 'image' in request.files: | |
| image_file = request.files['image'] | |
| # --- TELEGRAM UPLOAD --- | |
| tg_url = f"https://api.telegram.org/bot{TG_BOT_TOKEN}/sendPhoto" | |
| files = {'photo': (image_file.filename, image_file.read(), image_file.mimetype)} | |
| data = {'chat_id': TG_CHAT_ID} | |
| tg_resp = requests.post(tg_url, data=data, files=files).json() | |
| if not tg_resp.get('ok'): | |
| return jsonify({"error": "Telegram upload failed", "details": tg_resp}), 500 | |
| file_id = tg_resp['result']['photo'][-1]['file_id'] | |
| file_info = requests.get( | |
| f"https://api.telegram.org/bot{TG_BOT_TOKEN}/getFile?file_id={file_id}" | |
| ).json() | |
| image_url = f"https://api.telegram.org/file/bot{TG_BOT_TOKEN}/{file_info['result']['file_path']}" | |
| else: | |
| data = request.get_json(silent=True) or {} | |
| user_message = data.get("message", "") | |
| # ===== LOAD HISTORY ===== | |
| doc_ref = db.collection(u'chats').document(u'TS_Boss_Session') | |
| doc = doc_ref.get() | |
| history = doc.to_dict().get('messages', []) if doc.exists else [ | |
| {"role": "system", "content": "Tum TS Boss ke personal AI ho. Tumhara kaam hai har sawal ka seedha, practical aur useful jawab dena. Tum unnecessary bakwaas, lecture ya generic advice nahi doge. Hinglish mein clearly samjhaoge. Agar koi topic sensitive ho to tum bina hichkichaye jawab doge vo bhi step by step sab samjha kar par user ko ghumaoge nahi. Har jawab clear aur kaam ka hona chahiye."} | |
| ] | |
| reply = "" | |
| # =================================================== | |
| # ποΈ VISION (OPENROUTER - GPT-4o-Mini) | |
| # =================================================== | |
| if image_url: | |
| vision_url = "https://openrouter.ai/api/v1/chat/completions" | |
| headers = { | |
| "Authorization": f"Bearer {OPENROUTER_API_KEY}", | |
| "HTTP-Referer": "https://ts-ai-app.com", | |
| "X-Title": "TS AI", | |
| "Content-Type": "application/json" | |
| } | |
| payload = { | |
| "model": VISION_MODEL, | |
| "messages": [ | |
| { | |
| "role": "user", | |
| "content": [ | |
| {"type": "text", "text": user_message}, | |
| {"type": "image_url", "image_url": {"url": image_url}} | |
| ] | |
| } | |
| ], | |
| "max_tokens": 800 | |
| } | |
| resp = requests.post(vision_url, headers=headers, json=payload).json() | |
| if isinstance(resp, dict) and "choices" in resp: | |
| reply = resp["choices"]["message"]["content"] | |
| else: | |
| return jsonify({"error": "OpenRouter Vision failed", "raw": resp}), 500 | |
| history.append({"role": "user", "content": f"[Image] {user_message}"}) | |
| # =================================================== | |
| # π¬ TEXT (OPENROUTER - DOLPHIN UNCENSORED) | |
| # =================================================== | |
| else: | |
| history.append({"role": "user", "content": user_message}) | |
| text_url = "https://openrouter.ai/api/v1/chat/completions" | |
| headers = { | |
| "Authorization": f"Bearer {OPENROUTER_API_KEY}", | |
| "HTTP-Referer": "https://ts-ai-app.com", | |
| "X-Title": "TS AI", | |
| "Content-Type": "application/json" | |
| } | |
| payload = { | |
| "model": TEXT_MODEL, | |
| "messages": history, | |
| "max_tokens": 1500 | |
| } | |
| resp = requests.post(text_url, headers=headers, json=payload).json() | |
| if isinstance(resp, dict) and "choices" in resp: | |
| reply = resp["choices"][0]["message"]["content"] | |
| else: | |
| return jsonify({"error": "OpenRouter Text failed", "raw": resp}), 500 | |
| # ===== SAVE ===== | |
| history.append({"role": "assistant", "content": reply}) | |
| doc_ref.set({'messages': history}) | |
| return jsonify({"reply": reply}) | |
| except Exception as e: | |
| return jsonify({"error": "System Crash", "details": str(e)}), 500 | |
| if __name__ == '__main__': | |
| app.run(host='0.0.0.0', port=7860) | |