File size: 5,911 Bytes
64c77d4
02a40fb
64c77d4
 
 
 
 
 
 
02a40fb
64c77d4
02a40fb
1a9f910
 
02a40fb
 
1a9f910
 
 
02a40fb
64c77d4
97d41fe
02a40fb
661f72a
 
02a40fb
64c77d4
02a40fb
 
 
91f4345
64c77d4
 
02a40fb
64c77d4
 
 
1a9f910
 
 
 
64c77d4
02a40fb
1a9f910
02a40fb
1a9f910
 
02a40fb
 
1a9f910
 
 
02a40fb
aa3fb07
02a40fb
97d41fe
02a40fb
 
97d41fe
02a40fb
 
 
 
97d41fe
02a40fb
1a9f910
 
 
aa3fb07
02a40fb
1a9f910
 
02a40fb
 
 
64c77d4
97d41fe
 
02a40fb
 
 
aa3fb07
02a40fb
 
 
 
 
 
 
 
 
13e303a
 
02a40fb
 
 
 
 
 
 
 
 
 
13e303a
02a40fb
 
 
1a9f910
91f4345
39a970b
02a40fb
 
 
 
 
 
 
16a1744
aa3fb07
02a40fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97d41fe
 
 
02a40fb
aa3fb07
02a40fb
33d039b
64c77d4
02a40fb
64c77d4
aa3fb07
64c77d4
02a40fb
 
64c77d4
 
91f4345
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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

@app.route('/', methods=['GET'])
def home():
    return jsonify({"status": "TS AI Secure Brain (Uncensored Mode) Running ๐Ÿš€"})

@app.route('/api/chat', methods=['POST'])
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)