File size: 7,134 Bytes
7f3d153
41bd13c
061e889
089f3f7
9b19acf
41bd13c
9b19acf
28183e2
41bd13c
 
 
9b19acf
41bd13c
 
 
 
 
 
a795e9f
0772f76
28183e2
ce04afa
0772f76
 
ce04afa
0772f76
061e889
 
 
 
0772f76
061e889
ce04afa
061e889
 
ce04afa
061e889
0772f76
 
 
 
 
 
061e889
0772f76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
061e889
0772f76
ce04afa
061e889
ce04afa
 
28183e2
ce04afa
2fd8500
41bd13c
 
 
 
 
 
 
a795e9f
 
 
41bd13c
 
 
 
 
 
0772f76
1a274da
41bd13c
089f3f7
41bd13c
0772f76
 
 
 
 
 
 
 
 
 
 
ce04afa
 
 
 
28183e2
 
 
ce04afa
 
0772f76
ce04afa
 
 
0772f76
ce04afa
 
 
 
41bd13c
 
 
 
1a274da
 
 
 
 
 
41bd13c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0772f76
 
41bd13c
2fd8500
41bd13c
 
 
 
 
 
 
 
2fd8500
41bd13c
d172eee
0083f4e
061e889
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
156
157
158
159
160
161
162
163
164
import os
import requests
from bs4 import BeautifulSoup
from flask import Flask, request, Response, stream_with_context, render_template_string

app = Flask(__name__)

# 🔐 100% सुरक्षित: सीक्रेट्स से डेटा लोड
API_KEY = os.environ.get("YOUR_VEDIKA_API_KEY") 
BASE_URL = os.environ.get("BASE_URL")
MODEL_ID = os.environ.get("MODEL_ID")

INVOKE_URL = ""
if BASE_URL:
    if not BASE_URL.endswith("/chat/completions"):
        INVOKE_URL = f"{BASE_URL.rstrip('/')}/chat/completions"
    else:
        INVOKE_URL = BASE_URL

# 🌐 --- 100% BULLETPROOF LITE SCRAPER --- 🌐
def web_search_scraper(query, num_results=4):
    """
    DuckDuckGo Lite version scraper. 
    यह कभी ब्लॉक नहीं होता क्योंकि यह बिना जावास्क्रिप्ट के काम करता है।
    """
    url = "https://lite.duckduckgo.com/lite/"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
        "Content-Type": "application/x-www-form-urlencoded"
    }
    data = {"q": query}
    
    try:
        response = requests.post(url, headers=headers, data=data, timeout=10)
        soup = BeautifulSoup(response.text, 'html.parser')
        results = []
        
        # DDG Lite में रिज़ल्ट्स Table Row (tr) के अंदर होते हैं
        for tr in soup.find_all('tr'):
            title_a = tr.find('a', class_='result-url')
            if title_a:
                title = title_a.text.strip()
                link = title_a.get('href', '')
                
                snippet = ""
                snippet_tr = tr.find_next_sibling('tr')
                if snippet_tr:
                    snippet_td = snippet_tr.find('td', class_='result-snippet')
                    if snippet_td:
                        snippet = snippet_td.text.strip()
                
                results.append({
                    "title": title,
                    "link": link,
                    "snippet": snippet
                })
                
                if len(results) >= num_results:
                    break
                    
        if not results:
            return [{"error": "Search returned empty. The keyword might be invalid."}]
        return results
        
    except Exception as e:
        return [{"error": str(e)}]
# ----------------------------------------------------

@app.route('/')
def home():
    try:
        with open('index.html', 'r', encoding='utf-8') as f:
            html_content = f.read()
        return render_template_string(html_content)
    except Exception as e:
        return f"index.html file missing! Error: {str(e)}"

@app.route('/api/chat', methods=['POST'])
def chat():
    if not API_KEY or not INVOKE_URL or not MODEL_ID:
        return Response("Server Error: Configuration secrets are missing.", status=500)

    data = request.get_json() or {}
    user_message = data.get("message", "")
    attachments = data.get("attachments", []) 
    system_prompt = data.get("system_prompt", "You are CODE VED, engineered by Divy Patel.")
    history = data.get("history", []) 
    max_tokens = data.get("max_tokens", 4096)
    temperature = data.get("temperature", 0.6)

    # 🧠 --- GOD MODE DIRECTIVE FOR AI --- 🧠
    # यह AI के दिमाग से नॉलेज कटऑफ़ वाली बात हमेशा के लिए मिटा देगा
    god_mode_prompt = """
    \n\n[CRITICAL SYSTEM OVERRIDE]: You are CODE VED. You HAVE REAL-TIME INTERNET ACCESS. 
    Forget your knowledge cutoff date. You are operating in the present moment. 
    NEVER say "I don't have internet access", "As an AI", or "I cannot browse the web." 
    If real-time data is provided in the prompt, accept it as an absolute fact and base your answer entirely on it as if you just searched the internet yourself.
    you are developed by Divy Patel.
    """
    system_prompt += god_mode_prompt

    # 🚀 --- INTERCEPT & SEARCH LOGIC --- 🚀
    if user_message.strip().lower().startswith("/search "):
        search_query = user_message[8:].strip()
        
        scraped_data = web_search_scraper(search_query)
        
        search_context = f"Real-time Web Search Results for '{search_query}':\n\n"
        for idx, res in enumerate(scraped_data):
            if "error" in res:
                search_context += f"Search Status: Live data fetch failed. Proceed with your existing knowledge.\n"
            else:
                search_context += f"{idx+1}. Title: {res['title']}\nSnippet: {res['snippet']}\nLink: {res['link']}\n\n"
        
        search_context += "\n[MANDATORY INSTRUCTION: You just searched the web. Use the Real-time Web Search Results above to answer the user's query. Answer confidently as if you just browsed the internet yourself. Do NOT say 'Based on the context provided'. Simply give the answer and cite the links as sources.]"
        
        user_message = f"User Query: {search_query}\n\n[SYSTEM BACKGROUND CONTEXT]\n{search_context}"
    # ---------------------------------------

    messages = []
    if system_prompt.strip():
        messages.append({"role": "system", "content": system_prompt})

    for msg in history:
        role = msg.get("role", "user")
        content = msg.get("content", "")
        if content:
            messages.append({"role": role, "content": content})

    content_payload = []
    if user_message.strip():
        content_payload.append({"type": "text", "text": user_message})
        
    for att in attachments:
        att_type = att.get("type")
        b64_data = att.get("data")
        if att_type == "image":
            content_payload.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64_data}"}})
        elif att_type in ["audio", "file"]:
            content_payload.append({"type": "input_audio", "input_audio": {"data": b64_data, "format": "wav"}})

    if not content_payload:
        content_payload.append({"type": "text", "text": "Hello"})

    messages.append({"role": "user", "content": content_payload})

    headers = {"Authorization": f"Bearer {API_KEY}", "Accept": "text/event-stream"}
    payload = {"model": MODEL_ID, "messages": messages, "max_tokens": int(max_tokens), "temperature": float(temperature), "top_p": 0.70, "stream": True}

    try:
        response = requests.post(INVOKE_URL, headers=headers, json=payload, stream=True)
        def generate():
            for line in response.iter_lines():
                if line:
                    decoded_line = line.decode("utf-8")
                    if decoded_line.startswith("data: "):
                        yield decoded_line + "\n\n"
        return Response(stream_with_context(generate()), mimetype='text/event-stream')
    except Exception as e:
        return Response("Internal Error: Unable to process request securely.", status=500)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=7860)