rawr / app.py
aaronjpi's picture
Upload 3 files
6e61234 verified
Raw History Blame Contribute Delete
3.12 kB
import os
import re
import gradio as gr
from PIL import Image
from transformers import pipeline
MODEL_NAME = os.getenv("HF_MODEL", "google/flan-t5-small")
def load_model():
try:
return pipeline(
"text2text-generation",
model=MODEL_NAME,
device=-1,
)
except Exception:
return None
def clean_answer(text: str) -> str:
text = text.strip()
text = re.sub(r"\n{3,}", "\n\n", text)
text = text.replace("\\n", "\n")
return text
def build_prompt(question: str, image_file=None) -> str:
prompt = f"""
You are a patient economics tutor for a community college course.
Solve the question carefully and show the work in a clear, educational way.
Requirements:
- Show step-by-step reasoning with formulas and intermediate calculations.
- Explain what the problem is asking before solving it.
- If there is a graph, describe the axes, curves, and equilibrium.
- Keep the final answer concise and readable.
- If the problem is missing data, say what is missing and how you would solve it.
Question:
{question}
"""
if image_file is not None:
prompt += "\nThe user also uploaded an image of the question. Read the image carefully and use it as context for your answer."
return prompt
def solve_econ(question: str, image_file=None) -> str:
question = (question or "").strip()
if not question and image_file is None:
return "Please type a question or upload an image before solving."
if not question and image_file is not None:
question = "Please read the uploaded image and solve the economics question shown in it."
model = load_model()
if model is None:
return "The free model could not be loaded in this Space. Please paste the question text instead of relying on the image alone."
prompt = build_prompt(question, image_file)
result = model(prompt, max_length=400, do_sample=False)
answer = result[0]["generated_text"] if result else "No answer generated."
return clean_answer(answer)
with gr.Blocks(title="Econ Solve Bot") as demo:
gr.Markdown("# Econ Solve Bot")
gr.Markdown("Upload a question image or paste the problem. This free public Space is tuned for a lightweight CPU model.")
with gr.Row():
with gr.Column(scale=1):
question = gr.Textbox(
label="Question",
lines=8,
placeholder="Example: If the price of a good rises from $10 to $12 and quantity demanded falls from 50 to 40, what is the price elasticity of demand?",
)
image = gr.Image(label="Optional question image", type="pil")
submit = gr.Button("Solve it", variant="primary")
with gr.Column(scale=1):
output = gr.Textbox(label="Step-by-step solution", lines=20)
submit.click(fn=solve_econ, inputs=[question, image], outputs=output)
gr.Markdown("---")
gr.Markdown("This version is optimized for a free Hugging Face Space. For the most reliable answers, paste the text problem directly.")
if __name__ == "__main__":
demo.launch()