mmdbes commited on
Commit
0b0f809
·
verified ·
1 Parent(s): 436c9ab

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -67
app.py CHANGED
@@ -1,79 +1,85 @@
1
  # app.py
2
 
 
3
  import torch
4
  from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
5
- import gradio as gr
6
  import os
7
 
8
- # --- 1. Model Configuration and Loading ---
9
- # This part runs only once when the app starts.
 
 
 
 
10
 
11
- print("--- Setting up for CPU ---")
12
- device = "cpu"
13
- torch_dtype = torch.float32 # Use float32 for CPU
14
 
15
- model_id = "vhdm/whisper-large-fa-v1"
 
 
 
16
 
17
- print("--- Loading model and processor ---")
18
- # Load the model and processor
19
- model = AutoModelForSpeechSeq2Seq.from_pretrained(
20
- model_id,
21
- torch_dtype=torch_dtype,
22
- low_cpu_mem_usage=True,
23
- use_safetensors=True # Safetensors is generally preferred
24
- )
25
- processor = AutoProcessor.from_pretrained(model_id)
26
-
27
- # Create the pipeline
28
- print("--- Creating transcription pipeline ---")
29
- pipe = pipeline(
30
- "automatic-speech-recognition",
31
- model=model,
32
- tokenizer=processor.tokenizer,
33
- feature_extractor=processor.feature_extractor,
34
- max_new_tokens=128,
35
- torch_dtype=torch_dtype,
36
- device=device,
37
- )
38
 
39
- print("--- Setup complete. Gradio app is ready. ---")
40
-
41
- # --- 2. The Transcription Function ---
42
- # This function is called every time a user uploads a file.
43
-
44
- def transcribe_audio(audio_filepath):
45
- """
46
- Takes an audio file path, transcribes it, and returns the text.
47
- """
48
- if audio_filepath is None:
49
- return "Please upload an audio file first."
50
-
51
- print(f"Processing file: {audio_filepath}")
52
- result = pipe(audio_filepath, return_timestamps=True)
53
- transcription = result["text"]
54
- print(f"Transcription result: {transcription}")
55
-
56
- return transcription
57
-
58
- # --- 3. Gradio Web Interface ---
59
-
60
- # Define the title and description for the web app
61
- title = "Whisper Persian ASR 🇮🇷"
62
- description = """
63
- This is a demo for the `vhdm/whisper-large-fa-v1` model for automatic speech recognition (ASR) in Persian.
64
- <br>
65
- Upload your audio file (MP3, WAV, etc.) or record directly from your microphone and click 'Submit' to see the transcription.
66
- """
67
-
68
- # Create the Gradio interface
69
- iface = gr.Interface(
70
- fn=transcribe_audio,
71
- inputs=gr.Audio(type="filepath", label="Upload or Record Persian Audio"),
72
- outputs=gr.Textbox(label="Transcription Result"),
73
- title=title,
74
- description=description,
75
- examples=[["example.wav"]] # Optional: add an example file
 
76
  )
77
 
78
- # Launch the app
79
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # app.py
2
 
3
+ import streamlit as st
4
  import torch
5
  from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
 
6
  import os
7
 
8
+ # --- 1. تنظیمات اولیه و عنوان صفحه ---
9
+ st.set_page_config(
10
+ page_title="Persian Whisper ASR",
11
+ page_icon="🇮🇷🎙️",
12
+ layout="centered"
13
+ )
14
 
15
+ st.title("🇮🇷 اپلیکیشن تبدیل گفتار به نوشتار فارسی (Whisper)")
 
 
16
 
17
+ st.markdown("""
18
+ این یک نسخه نمایشی برای مدل **`vhdm/whisper-large-fa-v1`** است.
19
+ فایل صوتی خود را آپلود کنید تا متن آن را مشاهده نمایید.
20
+ """)
21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ # --- 2. بارگذاری مدل (با کش کردن برای سرعت بیشتر) ---
24
+ # این دکوراتور به Streamlit می‌گوید که مدل را فقط یک بار بارگذاری کند.
25
+ @st.cache_resource
26
+ def load_model():
27
+ """Loads and caches the Whisper model and processor."""
28
+ print("--- Loading model and processor for the first time ---")
29
+ device = "cpu"
30
+ torch_dtype = torch.float32
31
+
32
+ model_id = "vhdm/whisper-large-fa-v1"
33
+
34
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
35
+ model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True
36
+ )
37
+ processor = AutoProcessor.from_pretrained(model_id)
38
+
39
+ pipe = pipeline(
40
+ "automatic-speech-recognition",
41
+ model=model,
42
+ tokenizer=processor.tokenizer,
43
+ feature_extractor=processor.feature_extractor,
44
+ max_new_tokens=128,
45
+ torch_dtype=torch_dtype,
46
+ device=device,
47
+ )
48
+ print("--- Model loaded successfully ---")
49
+ return pipe
50
+
51
+ # مدل را بارگذاری می‌کنیم
52
+ transcription_pipe = load_model()
53
+
54
+
55
+ # --- 3. بخش آپلود فایل و پردازش ---
56
+
57
+ st.header("فایل صوتی خود را آپلود کنید")
58
+ uploaded_file = st.file_uploader(
59
+ "یک فایل صوتی انتخاب کنید (WAV, MP3, FLAC)...",
60
+ type=["wav", "mp3", "m4a", "flac"]
61
  )
62
 
63
+ if uploaded_file is not None:
64
+ # نمایش فایل صوتی
65
+ st.audio(uploaded_file, format='audio/wav')
66
+
67
+ # دکمه برای شروع پردازش
68
+ if st.button("شروع رونویسی"):
69
+ # برای پردازش، فایل را به صورت موقت ذخیره می‌کنیم
70
+ temp_file_path = f"./temp_{uploaded_file.name}"
71
+ with open(temp_file_path, "wb") as f:
72
+ f.write(uploaded_file.getbuffer())
73
+
74
+ # نمایش پیام در حال پردازش
75
+ with st.spinner("در حال پردازش فایل صوتی... لطفاً صبر کنید."):
76
+ result = transcription_pipe(temp_file_path)
77
+ transcription = result["text"]
78
+
79
+ # نمایش نتیجه
80
+ st.success("پردازش با موفقیت انجام شد!")
81
+ st.subheader("متن رونویسی شده:")
82
+ st.write(transcription)
83
+
84
+ # حذف فایل موقت
85
+ os.remove(temp_file_path)