Piyush-0019/Problem_solver
1
1import os2import subprocess3import threading4from http.server import HTTPServer, BaseHTTPRequestHandler5from telegram import Update6from telegram.ext import ApplicationBuilder, MessageHandler, filters, ContextTypes7from google import genai8from PIL import Image9 10# 1. Dummy HTTP Server (Keeps the cloud space active on port 7860)11class HealthCheckHandler(BaseHTTPRequestHandler):12 def do_GET(self):13 self.send_response(200)14 self.end_headers()15 self.wfile.write(b"Bot is online and processing PDFs!")16 17def run_dummy_server():18 server_address = ('0.0.0.0', 7860)19 httpd = HTTPServer(server_address, HealthCheckHandler)20 httpd.serve_forever()21 22threading.Thread(target=run_dummy_server, daemon=True).start()23 24# 2. Initialize Gemini API via Secure Environment Variable25client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))26 27async def process_image(update: Update, context: ContextTypes.DEFAULT_TYPE):28 await update.message.reply_text("Image received! Generating equations...")29 30 # Download image from the Telegram chat31 photo_file = await update.message.photo[-1].get_file()32 image_path = "temp_question.jpg"33 await photo_file.download_to_drive(image_path)34 35 try:36 image = Image.open(image_path)37 prompt = """38 Solve the problem in the image. 39 Output ONLY valid, compilable code using the article class. 40 Do not include markdown formatting. Start directly with \\documentclass.41 """42 43 response = client.models.generate_content(44 model="gemini-3.5-flash",45 contents=[image, prompt]46 )47 48 latex_code = response.text.strip()49 50 # Clean up markdown backticks safely without complex text breaks51 if latex_code.startswith("```latex"):52 latex_code = latex_code[8:]53 elif latex_code.startswith("```"):54 latex_code = latex_code[3:]55 56 if latex_code.endswith("```"):57 latex_code = latex_code[:-3]58 59 latex_code = latex_code.strip()60 61 tex_filename = "solution.tex"62 with open(tex_filename, "w", encoding="utf-8") as file:63 file.write(latex_code)64 65 await update.message.reply_text("Code written. Compiling PDF on cloud server...")66 67 # Compile PDF inside the Docker container68 subprocess.run(["pdflatex", "-interaction=nonstopmode", tex_filename], check=True)69 70 # Send PDF back to the user71 pdf_filename = "solution.pdf"72 with open(pdf_filename, "rb") as pdf_file:73 await update.message.reply_document(74 document=pdf_file, 75 filename="solution.pdf",76 caption="Here is your compiled PDF solution!"77 )78 79 except subprocess.CalledProcessError:80 await update.message.reply_text("PDF compilation failed due to LaTeX syntax errors.")81 except Exception as e:82 await update.message.reply_text(f"An error occurred: {e}")83 finally:84 # Clean up temporary files for the next request85 for file in ["temp_question.jpg", "solution.tex", "solution.pdf", "solution.aux", "solution.log"]:86 if os.path.exists(file):87 os.remove(file)88 89if __name__ == '__main__':90 # Start the Telegram Bot via Secure Environment Variable91 bot_token = os.environ.get("TELEGRAM_BOT_TOKEN")92 app = ApplicationBuilder().token(bot_token).build()93 app.add_handler(MessageHandler(filters.PHOTO, process_image))94 app.run_polling()95 