Spaces:
Running
Running
File size: 2,900 Bytes
8924524 | 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 | 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) |