umaradnaan's picture
Update app.py
9359b21 verified
import gradio as gr
import speech_recognition as sr
import re
# ------------------------------------------
# Convert spoken text โ†’ math expression
# ------------------------------------------
def words_to_expression(text):
text = text.lower()
# Word โ†’ symbol mapping
replacements = {
"plus": "+",
"add": "+",
"minus": "-",
"subtract": "-",
"into": "*",
"multiply": "*",
"times": "*",
"x": "*",
"divide": "/",
"by": "/",
"mod": "%",
"power": "**"
}
# Replace words with symbols
for word, symbol in replacements.items():
text = text.replace(word, symbol)
# Remove any unwanted characters
expression = re.sub(r"[^0-9+\-*/%.() ]", "", text)
return expression
# ------------------------------------------
# Speech Recognition + Calculator
# ------------------------------------------
def voice_calculator(audio):
if audio is None:
return "โŒ No audio detected! Try again."
recognizer = sr.Recognizer()
try:
with sr.AudioFile(audio) as source:
audio_data = recognizer.record(source)
text = recognizer.recognize_google(audio_data)
expression = words_to_expression(text)
# Try evaluating the math expression
try:
result = eval(expression)
except Exception:
return f"๐ŸŽค You said: {text}\nโŒ Could not understand math expression."
return f"๐ŸŽค You said: {text}\n๐Ÿงฎ Expression: {expression}\nโœ… Result: {result}"
except sr.UnknownValueError:
return "โŒ Could not understand your voice"
except Exception as e:
return f"โš ๏ธ Error: {str(e)}"
# ------------------------------------------
# Gradio UI
# ------------------------------------------
app = gr.Interface(
fn=voice_calculator,
inputs=gr.Audio(type="filepath", sources=["microphone"], label="๐ŸŽค Speak your calculation"),
outputs="text",
title="๐ŸŽค Voice Calculator",
description="Speak: 'five plus ten', 'twenty divided by five', 'thirty into two', etc."
)
app.launch()