Spaces:
Sleeping
Sleeping
| 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() | |