math-scan-processor / math_solver.py
sh4lu-z's picture
Upload 2 files
8924524 verified
import cv2
import base64
import requests
import json
import sys
import io
# UTF-8 Encoding ΰΆ…ΰΆ±ΰ·’ΰ·€ΰ·ΰΆ»ΰ·ŠΰΆΊΰΆΊΰ·’ (ࢱැࢭ්ࢱࢸ් xΒ² ΰΆ…ΰΆšΰ·”ΰΆ» Print ΰ·€ΰ·™ΰΆ―ΰ·ŠΰΆ―ΰ·’ Error ࢑ࢱවා)
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
def solve_math_problem(image_path, user_prompt=""):
img = cv2.imread(image_path)
if img is None:
print("❌ Error: Image not found!")
return
# Image Resize Logic
height, width = img.shape[:2]
max_width = 768
if width > max_width:
ratio = max_width / width
new_height = int(height * ratio)
img = cv2.resize(img, (max_width, new_height), interpolation=cv2.INTER_AREA)
_, buffer = cv2.imencode('.jpg', img)
base64_image = base64.b64encode(buffer).decode('utf-8')
data_url = f"data:image/jpeg;base64,{base64_image}"
if not user_prompt.strip():
final_instruction = "Solve this accurately."
else:
final_instruction = f"User Request: {user_prompt}"
# πŸ”₯ ΰ·€ΰ·’ΰ·ΰ·šΰ·‚ Prompt ΰΆ‘ΰΆš (Formatting Rules)
prompt_text = f"""You are a math tutor on WhatsApp.
CRITICAL FORMATTING RULES (Follow these strictly):
1. 🚫 NEVER use the caret symbol (^).
- CORRECT: x², y³, 10⁡
- WRONG: x^2, y^3
2. 🚫 NEVER use asterisk (*) for multiplication.
- CORRECT: 3x Γ— 2y
- WRONG: 3x * 2y
3. 🚫 NEVER use standard slash (/) for division steps if confusing.
- Use 'Γ·' or write clearly.
4. Write algebraic terms naturally (e.g., 3xΒ² + 2x + 5).
LAYOUT:
🎯 **Answer:** [Final Result in Bold]
──────────────────
πŸ“ **Steps:**
[Use Emojis πŸ”Ή for bullet points. Keep sentences short.]
──────────────────
INSTRUCTION: {final_instruction}"""
url = "https://text.pollinations.ai/"
payload = {
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": prompt_text},
{"type": "image_url", "image_url": {"url": data_url}}
]
}
],
"model": "gemini",
"jsonMode": False
}
try:
response = requests.post(url, json=payload, headers={"Content-Type": "application/json"})
response.encoding = 'utf-8'
if response.status_code == 200:
print(response.text)
else:
print("❌ AI Error.")
except Exception as e:
print(f"❌ Connection Error: {str(e)}")
if __name__ == "__main__":
img_file = sys.argv[1] if len(sys.argv) > 1 else "math.png"
u_prompt = sys.argv[2] if len(sys.argv) > 2 else ""
solve_math_problem(img_file, u_prompt)