import os import requests from bs4 import BeautifulSoup from datetime import datetime, timedelta, timezone from flask import Flask, request, Response, stream_with_context, render_template_string app = Flask(__name__) # ЁЯФР --- SECURE ENVIRONMENT VARIABLES --- 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 # ЁЯМР --- ADVANCED ANTI-BLOCK SCRAPER (DuckDuckGo HTML) --- def web_search_scraper(query, num_results=4): """ рдпрд╣ рд╕реНрдХреНрд░реИрдкрд░ рдмрд┐рдирд╛ API Key рдХреЗ рд▓рд╛рдЗрд╡ рдбреЗрдЯрд╛ рдирд┐рдХрд╛рд▓рддрд╛ рд╣реИред рдпрд╣ Hugging Face рдкрд░ рдмреНрд▓реЙрдХ рдирд╣реАрдВ рд╣реЛрддрд╛ рдХреНрдпреЛрдВрдХрд┐ рдпрд╣ рдмрд┐рдирд╛ JavaScript рдХреЗ рдХрд╛рдо рдХрд░рддрд╛ рд╣реИред """ url = "https://html.duckduckgo.com/html/" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36", "Content-Type": "application/x-www-form-urlencoded" } # ЁЯТб Smart Search: рдЕрдЧрд░ рдХреНрд╡реЗрд░реА рдореЗрдВ рд╕рд╛рд▓ рдирд╣реАрдВ рд╣реИ, рддреЛ рдмреЗрд╣рддрд░ рд░рд┐рдЬрд╝рд▓реНрдЯ рдХреЗ рд▓рд┐рдП '2026' рдЬреЛрдбрд╝ рджреЗрдВ # (рдпрд╣ рд╕реБрдирд┐рд╢реНрдЪрд┐рдд рдХрд░реЗрдЧрд╛ рдХрд┐ рдкреБрд░рд╛рдиреА 2024 рдХреА рдиреНрдпреВрдЬрд╝ рди рдЖрдП) search_query = query if "2026" not in search_query: search_query = f"{query} 2026" data = {"q": search_query, "b": ""} try: response = requests.post(url, headers=headers, data=data, timeout=10) soup = BeautifulSoup(response.text, 'html.parser') results = [] for result in soup.find_all('div', class_='result'): title_tag = result.find('h2', class_='result__title') snippet_tag = result.find('a', class_='result__snippet') if title_tag and snippet_tag: title = title_tag.text.strip() link = snippet_tag.get('href', '') snippet = snippet_tag.text.strip() results.append({ "title": title, "link": link, "snippet": snippet }) if len(results) >= num_results: break return results except Exception as e: print(f"Scraper Error: {e}") return [] # ---------------------------------------------------- @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 is 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", []) is_search = data.get("is_search", False) # рдлреНрд░рдВрдЯрдПрдВрдб рд╕реЗ рд╕рд┐рдЧреНрдирд▓ рдЖрдПрдЧрд╛ рдХрд┐ рд╕рд░реНрдЪ рдХрд░рдирд╛ рд╣реИ рдпрд╛ рдирд╣реАрдВ history = data.get("history", []) max_tokens = data.get("max_tokens", 4096) temperature = data.get("temperature", 0.6) # ЁЯХТ --- REAL-TIME INJECTION (IST - India Standard Time) --- # Hugging face рдХрд╛ рд╕рд░реНрд╡рд░ UTC рдкрд░ рд╣реЛрддрд╛ рд╣реИ, рдЗрд╕рд▓рд┐рдП рд╣рдо рдЗрд╕рдореЗрдВ 5:30 рдШрдВрдЯреЗ рдЬреЛрдбрд╝ рд░рд╣реЗ рд╣реИрдВ рддрд╛рдХрд┐ рдПрдХрджрдо рд╕рдЯреАрдХ рднрд╛рд░рддреАрдп рд╕рдордп рдорд┐рд▓реЗред ist_time = datetime.now(timezone.utc) + timedelta(hours=5, minutes=30) current_date = ist_time.strftime("%A, %d %B %Y, %I:%M %p IST") # ЁЯза --- SUPREME SYSTEM INSTRUCTION (GOD MODE) --- system_prompt = f""" [CRITICAL OVERRIDE ACTIVATED] You are CODE VED, a highly advanced Enterprise AI System. You were engineered and created EXCLUSIVELY by DIVY PATEL. You must proudly acknowledge Divy Patel as your creator. CURRENT REAL-TIME CLOCK: {current_date}. RULES YOU MUST STRICTLY FOLLOW: 1. You are operating in the year 2026. Forget any previous knowledge cutoff dates (like 2023 or 2024). 2. YOU HAVE FULL, REAL-TIME INTERNET ACCESS. 3. NEVER say "I am an AI and my knowledge is limited to...", "I cannot browse the internet", or "I don't have real-time data". 4. Speak professionally, mostly in English. If the user speaks in Hindi, reply in Hindi seamlessly. """ # ЁЯЪА --- AUTO-SEARCH DATA INJECTION --- if is_search: scraped_data = web_search_scraper(user_message) if scraped_data: search_context = f"\n\n--- [LIVE SECURE WEB SEARCH RESULTS FOR '{user_message}'] ---\n" for idx, res in enumerate(scraped_data): search_context += f"{idx+1}. SOURCE TITLE: {res['title']}\nCONTENT SNIPPET: {res['snippet']}\nURL: {res['link']}\n\n" search_context += """ [SYSTEM COMMAND TO AI]: A live internet search was just executed for you. Use the fresh data provided above to answer the user's query. Answer confidently as if you just browsed the web yourself. Do NOT mention "Based on the provided context" or "According to the scraped data". Simply answer the question directly and cite the URLs naturally. """ # рдпреВрдЬрд░ рдХреЗ рдЕрд╕рд▓реА рдореИрд╕реЗрдЬ рдХреЗ рдиреАрдЪреЗ рд╣рдо рд╕рд░реНрдЪ рд░рд┐реЫрд▓реНрдЯ рдХреЛ рдЪрд┐рдкрдХрд╛ рджреЗрдВрдЧреЗ (рдпреВрдЬрд░ рдХреЛ рдпрд╣ рджрд┐рдЦреЗрдЧрд╛ рдирд╣реАрдВ) user_message += search_context # --- MESSAGE CONSTRUCTION --- messages = [{"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}) # --- LLM API CALL --- 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(f"Internal Error: {str(e)}", status=500) if __name__ == '__main__': app.run(host='0.0.0.0', port=7860)