Download app.py from Emin009/HAKEM: direct link, hf CLI and curl.
- Browser
- Download file 6.71 kB
-
https://huggingface.co/spaces/Emin009/HAKEM/resolve/main/app.py
- Command line
-
hf download hf://spaces/Emin009/HAKEM/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Emin009/HAKEM/resolve/main/app.py
6.71 kB
| """Local-first HAKEM demo, ready for a Gradio Space when hosting is available.""" | |
| import os | |
| import base64 | |
| from pathlib import Path | |
| os.environ.setdefault('GRADIO_ANALYTICS_ENABLED', 'False') | |
| import gradio as gr | |
| if os.getenv('HAKEM_DEVICE', 'cpu') == 'cuda': | |
| import spaces | |
| from scoring import compare, catalogue, waveform, LANGUAGES, load_model | |
| compare_impl = compare | |
| def run(audio, candidates, language, expected): | |
| try: | |
| # Validate in the Gradio process so errors stay readable and do not | |
| # consume a GPU allocation. The scorer repeats these checks itself. | |
| rows = catalogue(candidates) | |
| waveform(audio) | |
| if language not in LANGUAGES: | |
| raise ValueError('Choose a language from the menu.') | |
| if expected.strip() and expected.strip() not in rows: | |
| raise ValueError('The expected item must exactly match a candidate, or leave it blank.') | |
| return compare_impl(audio, candidates, language, expected) | |
| except ValueError as error: | |
| raise gr.Error(str(error)) from error | |
| CSS = """.gradio-container {max-width: 1050px !important;} | |
| #winner textarea, #baseline textarea {font-size: 22px; font-weight: 650;} | |
| """ | |
| if os.getenv('HAKEM_DEVICE', 'cpu') == 'cuda': | |
| # ZeroGPU requires model placement at startup, before allocating a real GPU. | |
| load_model() | |
| compare_impl = spaces.GPU(duration=60)(compare) | |
| with gr.Blocks(title='HAKEM · MauriAI', theme=gr.themes.Soft(primary_hue='green'), css=CSS, | |
| delete_cache=(300, 300)) as demo: | |
| logo = base64.b64encode((Path(__file__).parent / 'mauriai_logo.png').read_bytes()).decode('ascii') | |
| gr.HTML(f'<img src="data:image/png;base64,{logo}" alt="MauriAI" style="width:250px;max-width:100%;height:auto">') | |
| gr.Markdown('''# HAKEM · Hear an item. Select it from your list. | |
| **MauriAI · Mohamed Lamine Bewa · Mauritania** | |
| A frozen multilingual Whisper Tiny model scores your candidates directly against your recording. | |
| HAKEM subtracts a matched silence-reference score. **No task-specific weight training.** | |
| Compare it with **T-match: Whisper transcription → closest candidate**, using the same frozen model, | |
| recording, language prompt, and list. | |
| [Read the research preprint](https://doi.org/10.5281/zenodo.23326833) · | |
| This demo is an implementation preview; it is not an independent replication of the paper's benchmarks. | |
| ''') | |
| with gr.Row(): | |
| with gr.Column(): | |
| candidates = gr.Textbox(label='1 · Your candidate list', lines=8, | |
| value='Nouakchott\nNouadhibou\nAtar\nRosso\nKaédi\nZouérat', | |
| info='One item per line. 2–32 items. Include the item you will say.') | |
| language = gr.Dropdown(list(LANGUAGES), value='Hassaniya / Arabic', label='2 · Language prompt') | |
| gr.Markdown('Hassaniya uses Whisper’s Arabic prompt; Whisper has no dedicated Hassaniya language token.') | |
| expected = gr.Textbox(label='Expected item (optional, for checking only)', | |
| placeholder='Copy the candidate you will say', | |
| info='Used only to check the outputs; neither method receives this answer.') | |
| with gr.Column(): | |
| audio = gr.Audio(sources=['microphone', 'upload'], type='numpy', label='3 · Say one item (up to 12 seconds)') | |
| button = gr.Button('Compare HAKEM and T-match', variant='primary') | |
| with gr.Row(): | |
| winner = gr.Textbox(label='HAKEM · Selected item', interactive=False, elem_id='winner') | |
| baseline = gr.Textbox(label='T-match · Selected item', interactive=False, elem_id='baseline') | |
| transcript = gr.Textbox(label='Whisper Tiny · Actual transcription', interactive=False, lines=2) | |
| assessment = gr.Textbox(label='Check against your expected item', interactive=False, lines=2) | |
| table = gr.Dataframe(headers=['Candidate', 'HAKEM score', 'Speech log-likelihood', 'Silence log-likelihood', 'T-match text similarity'], | |
| datatype=['str', 'number', 'number', 'number', 'number'], interactive=False, | |
| label='Candidate scores · ordered by HAKEM score') | |
| with gr.Accordion('Understand the scores and implementation', open=False): | |
| gr.Markdown('''**Score:** sum of candidate-token log-probabilities with speech, minus the same sum with | |
| a two-second digital-silence reference. Both include the end token, use a leading space, the same language | |
| and transcription prompts, and standard Whisper audio padding. Higher wins; a score is **not a confidence percentage**. | |
| **T-match:** Whisper generates a transcript with a deterministic 10-beam decoder (128 new-token limit). | |
| The transcript and each candidate are lowercased and stripped to Unicode letters/numbers. T-match selects | |
| the highest normalized Levenshtein text similarity, from 0 to 1. This is a text resemblance score, not recognition | |
| confidence, and it is not comparable numerically with HAKEM's score. All ties are shown. The candidate list does | |
| not bias Whisper's transcript; it is used afterward for matching. Either method can win, both can be right, | |
| or both can be wrong. Single recordings do not establish overall superiority. | |
| **Scope:** the method selects among supplied items. It may select a wrong item when the spoken item is absent, | |
| the language prompt is unsuitable, or the speech is unclear. This demo rejects digitally silent input with an | |
| audio-energy guard; it has no validated unknown-item rejection system. The paper covers 22 evaluated languages; | |
| the menu is a small convenience subset, not evidence of equal quality in every language. | |
| **Implementation:** float32, frozen Whisper Tiny, at most 32 candidates. The hosted demo uses free ZeroGPU; | |
| local runs use CPU by default. The paper used GPU float16 for the | |
| headline experiments; latency and numerical behavior can differ. This demo does not estimate benchmark accuracy. | |
| **Audio handling:** audio is processed by the machine hosting this app. Gradio creates temporary audio files, | |
| scheduled for cleanup after about five minutes. Do not submit confidential recordings. The app does not train | |
| on your audio or deliberately save a recording collection. Private Hassaniya research recordings are excluded. | |
| ''') | |
| details = gr.JSON(label='Run details') | |
| button.click(run, [audio, candidates, language, expected], | |
| [winner, baseline, transcript, assessment, table, details], api_name='compare_items', concurrency_limit=1) | |
| if __name__ == '__main__': | |
| demo.queue(max_size=8).launch(server_name=os.getenv('HAKEM_HOST', '127.0.0.1'), | |
| server_port=int(os.getenv('PORT', '7860')), share=False, | |
| max_file_size='10mb', show_error=False) | |