import gradio as gr from transformers import pipeline import numpy as np # Load FREE models ocr_pipe = pipeline("image-to-text", model="microsoft/trocr-base-handwritten") similarity_pipe = pipeline("feature-extraction", model="sentence-transformers/all-MiniLM-L6-v2") def validate_answer(image, user_text, correct_answer): # OCR for handwritten text if image: ocr_result = ocr_pipe(image) user_text = ocr_result[0]['generated_text'] # Check clarity (rule-based) clarity = sum(c.isalnum() for c in user_text) / max(1, len(user_text)) if clarity < 0.7: return "⚠️ Handwriting unclear", "", "" # Semantic comparison embeddings = similarity_pipe([correct_answer, user_text]) similarity = np.dot(embeddings[0], embeddings[1]) return ( f"✅ Clarity: {clarity:.0%}", f"📝 Extracted: {user_text}", f"🔍 Similarity: {similarity:.0%}" ) # Create interface with gr.Blocks() as demo: gr.Markdown("# Free Answer Validator") with gr.Row(): image_input = gr.Image(label="Upload Handwritten Answer", type="pil") text_input = gr.Textbox(label="Or Type Answer Here") correct_input = gr.Textbox(label="Correct Answer", value="The Earth revolves around the Sun.") submit_btn = gr.Button("Validate") clarity_out = gr.Textbox(label="Clarity Check") extracted_out = gr.Textbox(label="Extracted Text") similarity_out = gr.Textbox(label="Similarity Score") submit_btn.click( validate_answer, inputs=[image_input, text_input, correct_input], outputs=[clarity_out, extracted_out, similarity_out] ) demo.launch()