Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,7 +6,7 @@ import firebase_admin
|
|
| 6 |
from firebase_admin import credentials, firestore
|
| 7 |
|
| 8 |
app = Flask(__name__)
|
| 9 |
-
CORS(app)
|
| 10 |
|
| 11 |
# --- FIREBASE SETUP ---
|
| 12 |
try:
|
|
@@ -15,21 +15,21 @@ try:
|
|
| 15 |
firebase_admin.initialize_app(cred)
|
| 16 |
db = firestore.client()
|
| 17 |
except Exception as e:
|
| 18 |
-
print(
|
| 19 |
|
| 20 |
# --- SECRETS ---
|
| 21 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 22 |
-
|
| 23 |
-
TG_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN")
|
| 24 |
-
TG_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID")
|
| 25 |
|
| 26 |
-
# MODELS
|
| 27 |
TEXT_MODEL = "Qwen/Qwen2.5-Coder-32B-Instruct"
|
| 28 |
-
VISION_MODEL = "
|
| 29 |
|
| 30 |
@app.route('/', methods=['GET'])
|
| 31 |
def home():
|
| 32 |
-
return jsonify({"status": "TS AI
|
| 33 |
|
| 34 |
@app.route('/api/chat', methods=['POST'])
|
| 35 |
def chat():
|
|
@@ -38,75 +38,114 @@ def chat():
|
|
| 38 |
user_message = ""
|
| 39 |
image_url = None
|
| 40 |
|
| 41 |
-
#
|
| 42 |
if is_form_data:
|
| 43 |
-
user_message = request.form.get("message", "
|
| 44 |
if 'image' in request.files:
|
| 45 |
image_file = request.files['image']
|
| 46 |
-
|
| 47 |
-
#
|
| 48 |
tg_url = f"https://api.telegram.org/bot{TG_BOT_TOKEN}/sendPhoto"
|
| 49 |
files = {'photo': (image_file.filename, image_file.read(), image_file.mimetype)}
|
| 50 |
data = {'chat_id': TG_CHAT_ID}
|
|
|
|
| 51 |
tg_resp = requests.post(tg_url, data=data, files=files).json()
|
| 52 |
-
|
| 53 |
if not tg_resp.get('ok'):
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
file_id = tg_resp['result']['photo'][-1]['file_id']
|
| 58 |
-
file_info = requests.get(
|
|
|
|
|
|
|
|
|
|
| 59 |
image_url = f"https://api.telegram.org/file/bot{TG_BOT_TOKEN}/{file_info['result']['file_path']}"
|
|
|
|
| 60 |
else:
|
| 61 |
data = request.get_json(silent=True) or {}
|
| 62 |
user_message = data.get("message", "")
|
| 63 |
|
| 64 |
-
#
|
| 65 |
doc_ref = db.collection(u'chats').document(u'TS_Boss_Session')
|
| 66 |
doc = doc_ref.get()
|
| 67 |
-
history = doc.to_dict().get('messages', []) if doc.exists else [
|
|
|
|
|
|
|
| 68 |
|
| 69 |
reply = ""
|
| 70 |
|
| 71 |
-
#
|
|
|
|
|
|
|
| 72 |
if image_url:
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
payload = {
|
| 76 |
"model": VISION_MODEL,
|
| 77 |
-
"messages": [
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
}
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
|
|
|
| 83 |
if isinstance(resp, dict) and "choices" in resp:
|
| 84 |
-
reply = resp["choices"]["message"]["content"]
|
| 85 |
else:
|
| 86 |
-
return jsonify({"error": "
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
else:
|
| 90 |
history.append({"role": "user", "content": user_message})
|
|
|
|
| 91 |
hf_url = "https://router.huggingface.co/v1/chat/completions"
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
resp = requests.post(hf_url, headers=headers, json=payload).json()
|
| 95 |
-
|
| 96 |
-
# STRICT RESPONSE PARSING (Yehi tha asli culprit pichli baar)
|
| 97 |
if isinstance(resp, dict) and "choices" in resp:
|
| 98 |
reply = resp["choices"][0]["message"]["content"]
|
| 99 |
else:
|
| 100 |
-
return jsonify({"error": "
|
| 101 |
|
| 102 |
-
#
|
| 103 |
history.append({"role": "assistant", "content": reply})
|
| 104 |
doc_ref.set({'messages': history})
|
|
|
|
| 105 |
return jsonify({"reply": reply})
|
| 106 |
|
| 107 |
except Exception as e:
|
| 108 |
-
return jsonify({"error": "
|
|
|
|
| 109 |
|
| 110 |
if __name__ == '__main__':
|
| 111 |
-
app.run(host='0.0.0.0', port=7860)
|
| 112 |
-
|
|
|
|
| 6 |
from firebase_admin import credentials, firestore
|
| 7 |
|
| 8 |
app = Flask(__name__)
|
| 9 |
+
CORS(app)
|
| 10 |
|
| 11 |
# --- FIREBASE SETUP ---
|
| 12 |
try:
|
|
|
|
| 15 |
firebase_admin.initialize_app(cred)
|
| 16 |
db = firestore.client()
|
| 17 |
except Exception as e:
|
| 18 |
+
print("Firebase error:", e)
|
| 19 |
|
| 20 |
# --- SECRETS ---
|
| 21 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 22 |
+
OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY")
|
| 23 |
+
TG_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN")
|
| 24 |
+
TG_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID")
|
| 25 |
|
| 26 |
+
# --- MODELS ---
|
| 27 |
TEXT_MODEL = "Qwen/Qwen2.5-Coder-32B-Instruct"
|
| 28 |
+
VISION_MODEL = "qwen/qwen2.5-vl-7b-instruct"
|
| 29 |
|
| 30 |
@app.route('/', methods=['GET'])
|
| 31 |
def home():
|
| 32 |
+
return jsonify({"status": "TS AI (OpenRouter Vision + HF Brain) ๐"})
|
| 33 |
|
| 34 |
@app.route('/api/chat', methods=['POST'])
|
| 35 |
def chat():
|
|
|
|
| 38 |
user_message = ""
|
| 39 |
image_url = None
|
| 40 |
|
| 41 |
+
# ===== INPUT HANDLE =====
|
| 42 |
if is_form_data:
|
| 43 |
+
user_message = request.form.get("message", "Explain this image")
|
| 44 |
if 'image' in request.files:
|
| 45 |
image_file = request.files['image']
|
| 46 |
+
|
| 47 |
+
# --- TELEGRAM UPLOAD ---
|
| 48 |
tg_url = f"https://api.telegram.org/bot{TG_BOT_TOKEN}/sendPhoto"
|
| 49 |
files = {'photo': (image_file.filename, image_file.read(), image_file.mimetype)}
|
| 50 |
data = {'chat_id': TG_CHAT_ID}
|
| 51 |
+
|
| 52 |
tg_resp = requests.post(tg_url, data=data, files=files).json()
|
| 53 |
+
|
| 54 |
if not tg_resp.get('ok'):
|
| 55 |
+
return jsonify({"error": "Telegram upload failed", "details": tg_resp}), 500
|
| 56 |
+
|
|
|
|
| 57 |
file_id = tg_resp['result']['photo'][-1]['file_id']
|
| 58 |
+
file_info = requests.get(
|
| 59 |
+
f"https://api.telegram.org/bot{TG_BOT_TOKEN}/getFile?file_id={file_id}"
|
| 60 |
+
).json()
|
| 61 |
+
|
| 62 |
image_url = f"https://api.telegram.org/file/bot{TG_BOT_TOKEN}/{file_info['result']['file_path']}"
|
| 63 |
+
|
| 64 |
else:
|
| 65 |
data = request.get_json(silent=True) or {}
|
| 66 |
user_message = data.get("message", "")
|
| 67 |
|
| 68 |
+
# ===== LOAD HISTORY =====
|
| 69 |
doc_ref = db.collection(u'chats').document(u'TS_Boss_Session')
|
| 70 |
doc = doc_ref.get()
|
| 71 |
+
history = doc.to_dict().get('messages', []) if doc.exists else [
|
| 72 |
+
{"role": "system", "content": "Tum TS Boss ke AI ho. Hinglish mein baat karo."}
|
| 73 |
+
]
|
| 74 |
|
| 75 |
reply = ""
|
| 76 |
|
| 77 |
+
# ===================================================
|
| 78 |
+
# ๐๏ธ VISION (OPENROUTER)
|
| 79 |
+
# ===================================================
|
| 80 |
if image_url:
|
| 81 |
+
vision_url = "https://openrouter.ai/api/v1/chat/completions"
|
| 82 |
+
|
| 83 |
+
headers = {
|
| 84 |
+
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
|
| 85 |
+
"HTTP-Referer": "https://your-app.com",
|
| 86 |
+
"X-Title": "TS AI",
|
| 87 |
+
"Content-Type": "application/json"
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
payload = {
|
| 91 |
"model": VISION_MODEL,
|
| 92 |
+
"messages": [
|
| 93 |
+
{
|
| 94 |
+
"role": "user",
|
| 95 |
+
"content": [
|
| 96 |
+
{"type": "text", "text": user_message},
|
| 97 |
+
{"type": "image_url", "image_url": {"url": image_url}}
|
| 98 |
+
]
|
| 99 |
+
}
|
| 100 |
+
],
|
| 101 |
+
"max_tokens": 800
|
| 102 |
}
|
| 103 |
+
|
| 104 |
+
resp = requests.post(vision_url, headers=headers, json=payload).json()
|
| 105 |
+
|
| 106 |
+
# SAFE PARSING
|
| 107 |
if isinstance(resp, dict) and "choices" in resp:
|
| 108 |
+
reply = resp["choices"][0]["message"]["content"]
|
| 109 |
else:
|
| 110 |
+
return jsonify({"error": "OpenRouter Vision failed", "raw": resp}), 500
|
| 111 |
+
|
| 112 |
+
history.append({"role": "user", "content": f"[Image] {user_message}"})
|
| 113 |
+
|
| 114 |
+
# ===================================================
|
| 115 |
+
# ๐ฌ TEXT (HUGGING FACE)
|
| 116 |
+
# ===================================================
|
| 117 |
else:
|
| 118 |
history.append({"role": "user", "content": user_message})
|
| 119 |
+
|
| 120 |
hf_url = "https://router.huggingface.co/v1/chat/completions"
|
| 121 |
+
|
| 122 |
+
headers = {
|
| 123 |
+
"Authorization": f"Bearer {HF_TOKEN}",
|
| 124 |
+
"Content-Type": "application/json"
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
payload = {
|
| 128 |
+
"model": TEXT_MODEL,
|
| 129 |
+
"messages": history,
|
| 130 |
+
"max_tokens": 1000
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
resp = requests.post(hf_url, headers=headers, json=payload).json()
|
| 134 |
+
|
|
|
|
| 135 |
if isinstance(resp, dict) and "choices" in resp:
|
| 136 |
reply = resp["choices"][0]["message"]["content"]
|
| 137 |
else:
|
| 138 |
+
return jsonify({"error": "HF failed", "raw": resp}), 500
|
| 139 |
|
| 140 |
+
# ===== SAVE =====
|
| 141 |
history.append({"role": "assistant", "content": reply})
|
| 142 |
doc_ref.set({'messages': history})
|
| 143 |
+
|
| 144 |
return jsonify({"reply": reply})
|
| 145 |
|
| 146 |
except Exception as e:
|
| 147 |
+
return jsonify({"error": "System Crash", "details": str(e)}), 500
|
| 148 |
+
|
| 149 |
|
| 150 |
if __name__ == '__main__':
|
| 151 |
+
app.run(host='0.0.0.0', port=7860)
|
|
|