TS447 commited on
Commit
97d41fe
·
verified ·
1 Parent(s): 1a9f910

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -19
app.py CHANGED
@@ -1,6 +1,5 @@
1
  import os
2
  import requests
3
- import time
4
  from flask import Flask, request, jsonify
5
  from flask_cors import CORS
6
  import firebase_admin
@@ -18,52 +17,58 @@ try:
18
  except Exception as e:
19
  print(f"Firebase Error: {e}")
20
 
21
- # --- SECRETS (Tijori) ---
22
  HF_TOKEN = os.environ.get("HF_TOKEN")
23
  GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
24
  TG_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN")
25
  TG_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID")
26
 
27
- # 2026 CURRENT MODELS
28
  TEXT_MODEL = "Qwen/Qwen2.5-Coder-32B-Instruct"
29
- VISION_MODEL = "meta-llama/llama-4-scout-17b-16e-instruct" # March 2026 Stable
30
 
31
  @app.route('/', methods=['GET'])
32
  def home():
33
- return jsonify({"status": "TS AI Brain (Bulletproof 2026) is Active! 🚀"})
34
 
35
  @app.route('/api/chat', methods=['POST'])
36
  def chat():
37
  try:
38
- # 1. PATA LAGAO REQUEST KYA HAI
39
  is_form_data = 'multipart/form-data' in request.content_type if request.content_type else False
40
  user_message = ""
41
  image_url = None
42
 
 
43
  if is_form_data:
44
- user_message = request.form.get("message", "Analyze this.")
45
  if 'image' in request.files:
46
  image_file = request.files['image']
47
- # --- TELEGRAM GODOWN 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
  tg_resp = requests.post(tg_url, data=data, files=files).json()
52
 
53
- if tg_resp.get('ok'):
54
- file_id = tg_resp['result']['photo'][-1]['file_id']
55
- file_info = requests.get(f"https://api.telegram.org/bot{TG_BOT_TOKEN}/getFile?file_id={file_id}").json()
56
- image_url = f"https://api.telegram.org/file/bot{TG_BOT_TOKEN}/{file_info['result']['file_path']}"
 
 
 
57
  else:
58
  data = request.get_json(silent=True) or {}
59
  user_message = data.get("message", "")
60
 
61
- # 2. LOAD HISTORY
62
  doc_ref = db.collection(u'chats').document(u'TS_Boss_Session')
63
  doc = doc_ref.get()
64
  history = doc.to_dict().get('messages', []) if doc.exists else [{"role": "system", "content": "Tum TS Boss ke AI ho. Hinglish mein baat karo."}]
65
 
66
- # 3. VISION CALL (GROQ) OR TEXT CALL (HF)
 
 
67
  if image_url:
68
  groq_url = "https://api.groq.com/openai/v1/chat/completions"
69
  headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
@@ -74,26 +79,33 @@ def chat():
74
  }
75
  resp = requests.post(groq_url, headers=headers, json=payload).json()
76
 
77
- # SAFE RESPONSE PARSING
78
  if isinstance(resp, dict) and "choices" in resp:
79
  reply = resp["choices"]["message"]["content"]
80
  else:
81
- return jsonify({"error": "Groq API ne error diya", "raw": resp}), 500
 
 
82
  else:
83
  history.append({"role": "user", "content": user_message})
84
  hf_url = "https://router.huggingface.co/v1/chat/completions"
85
  headers = {"Authorization": f"Bearer {HF_TOKEN}", "Content-Type": "application/json"}
86
  payload = {"model": TEXT_MODEL, "messages": history}
87
  resp = requests.post(hf_url, headers=headers, json=payload).json()
88
- reply = resp["choices"][0]["message"]["content"]
 
 
 
 
 
89
 
90
- # 4. SAVE & REPLY
91
  history.append({"role": "assistant", "content": reply})
92
  doc_ref.set({'messages': history})
93
  return jsonify({"reply": reply})
94
 
95
  except Exception as e:
96
- return jsonify({"error": "System Error", "details": str(e)}), 500
97
 
98
  if __name__ == '__main__':
99
  app.run(host='0.0.0.0', port=7860)
 
1
  import os
2
  import requests
 
3
  from flask import Flask, request, jsonify
4
  from flask_cors import CORS
5
  import firebase_admin
 
17
  except Exception as e:
18
  print(f"Firebase Error: {e}")
19
 
20
+ # --- SECRETS ---
21
  HF_TOKEN = os.environ.get("HF_TOKEN")
22
  GROQ_API_KEY = os.environ.get("GROQ_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 = "llama-3.2-90b-vision-preview" # Groq ka sabse active vision model
29
 
30
  @app.route('/', methods=['GET'])
31
  def home():
32
+ return jsonify({"status": "TS AI Brain (Crash-Proof Mode) is Active! 🚀"})
33
 
34
  @app.route('/api/chat', methods=['POST'])
35
  def chat():
36
  try:
 
37
  is_form_data = 'multipart/form-data' in request.content_type if request.content_type else False
38
  user_message = ""
39
  image_url = None
40
 
41
+ # 1. READ REQUEST
42
  if is_form_data:
43
+ user_message = request.form.get("message", "Is photo mein kya error hai?")
44
  if 'image' in request.files:
45
  image_file = request.files['image']
46
+
47
+ # 2. TELEGRAM UPLOAD WITH STRICT CHECK
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
+ # Agar Telegram ne photo block ki, toh yahi error aayega
55
+ return jsonify({"error": "Telegram upload fail", "details": tg_resp}), 500
56
+
57
+ file_id = tg_resp['result']['photo'][-1]['file_id']
58
+ file_info = requests.get(f"https://api.telegram.org/bot{TG_BOT_TOKEN}/getFile?file_id={file_id}").json()
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
+ # 3. HISTORY LOAD
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 [{"role": "system", "content": "Tum TS Boss ke AI ho. Hinglish mein baat karo."}]
68
 
69
+ reply = ""
70
+
71
+ # 4. VISION CALL (Agar Image Hai)
72
  if image_url:
73
  groq_url = "https://api.groq.com/openai/v1/chat/completions"
74
  headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
 
79
  }
80
  resp = requests.post(groq_url, headers=headers, json=payload).json()
81
 
82
+ # STRICT RESPONSE PARSING (Ab crash nahi hoga)
83
  if isinstance(resp, dict) and "choices" in resp:
84
  reply = resp["choices"]["message"]["content"]
85
  else:
86
+ return jsonify({"error": "Groq API Error", "raw_response": resp}), 500
87
+
88
+ # 5. TEXT CALL (Sirf Text Hai Toh)
89
  else:
90
  history.append({"role": "user", "content": user_message})
91
  hf_url = "https://router.huggingface.co/v1/chat/completions"
92
  headers = {"Authorization": f"Bearer {HF_TOKEN}", "Content-Type": "application/json"}
93
  payload = {"model": TEXT_MODEL, "messages": history}
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": "Hugging Face Text API Error", "raw_response": resp}), 500
101
 
102
+ # 6. SAVE AND RETURN
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": "Python Code Crash", "details": str(e)}), 500
109
 
110
  if __name__ == '__main__':
111
  app.run(host='0.0.0.0', port=7860)