Havyle commited on
Commit
de8e74f
·
verified ·
1 Parent(s): 5f10796

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -109
app.py CHANGED
@@ -1,110 +1,108 @@
1
- import torch
2
- import gradio as gr
3
- from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
4
-
5
- # --- PHẦN 1: CẤU HÌNH & LOAD MODEL ---
6
- DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
7
-
8
- # 1. Load PhoWhisper (Nhận dạng giọng nói)
9
- print("Đang tải model PhoWhisper...")
10
- asr_pipeline = pipeline(
11
- "automatic-speech-recognition",
12
- model="vinai/PhoWhisper-small",
13
- device=0 if torch.cuda.is_available() else -1
14
- )
15
-
16
- # 2. Load Model Dịch (ViT5)
17
- # LƯU Ý QUAN TRỌNG:
18
- # Bạn phải upload folder chứa model (tên là 'trained_model') lên cùng chỗ với file app.py trên Hugging Face
19
- # Sau đó sửa đường dẫn dưới đây thành "./trained_model"
20
- TRANSLATION_MODEL_PATH = "./trained_model"
21
-
22
- print(f"Đang tải model dịch...")
23
- try:
24
- trans_tokenizer = AutoTokenizer.from_pretrained(TRANSLATION_MODEL_PATH)
25
- trans_model = AutoModelForSeq2SeqLM.from_pretrained(TRANSLATION_MODEL_PATH).to(DEVICE)
26
- print("Load model dịch thành công!")
27
- except Exception as e:
28
- print(f"Lỗi load model dịch: {e}")
29
- trans_model = None
30
-
31
-
32
- # --- PHẦN 2: CÁC HÀM XỬ LÝ (LOGIC) ---
33
- def speech_to_text(audio_path):
34
- if audio_path is None: return ""
35
- try:
36
- output = asr_pipeline(audio_path)
37
- return output['text']
38
- except Exception as e:
39
- return f"Lỗi: {str(e)}"
40
-
41
- def text_to_gloss(vietnamese_text):
42
- if not vietnamese_text: return ""
43
- if trans_model is None: return "Lỗi: Chưa load được model dịch."
44
-
45
- input_text = f"vi: {vietnamese_text}"
46
- inputs = trans_tokenizer(input_text, return_tensors="pt", max_length=128, truncation=True).to(DEVICE)
47
-
48
- with torch.no_grad():
49
- outputs = trans_model.generate(
50
- inputs["input_ids"],
51
- max_length=128,
52
- num_beams=5,
53
- early_stopping=True
54
- )
55
-
56
- gloss_text = trans_tokenizer.decode(outputs[0], skip_special_tokens=True)
57
- return gloss_text.replace("vsl: ", "") if gloss_text.startswith("vsl: ") else gloss_text
58
-
59
- def full_pipeline(audio, text_input, mode):
60
- vietnamese_output = ""
61
- if mode == "Giọng nói (Microphone/File)" and audio is not None:
62
- vietnamese_output = speech_to_text(audio)
63
- elif mode == "Văn bản (Nhập tay)" and text_input:
64
- vietnamese_output = text_input
65
- else:
66
- return "Vui lòng nhập dữ liệu.", ""
67
-
68
- gloss_output = text_to_gloss(vietnamese_output)
69
- return vietnamese_output, gloss_output
70
-
71
-
72
- # --- PHẦN 3: GIAO DIỆN (UI) - ĐOẠN CODE CỦA BẠN ---
73
- custom_css = """
74
- .container {max-width: 1200px; margin: auto; padding-top: 20px}
75
- .header-text {text-align: center; font-family: 'Arial', sans-serif;}
76
- .uni-name {font-size: 24px; font-weight: bold; color: #003366; margin-bottom: 5px;}
77
- .faculty-name {font-size: 18px; font-weight: normal; color: #cc0000; margin-bottom: 20px;}
78
- .project-title {font-size: 28px; font-weight: bold; color: #2c3e50; margin-bottom: 10px; border-bottom: 2px solid #eee; padding-bottom: 10px;}
79
- .note-text {font-size: 14px; font-style: italic; color: #7f8c8d; margin-top: 20px; border-top: 1px solid #eee; padding-top: 10px;}
80
- .output-box {border: 1px solid #e0e0e0; background-color: #f9f9f9; border-radius: 8px;}
81
- """
82
-
83
- with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
84
- # ... (Dán phần giao diện của bạn vào đây, y hệt đoạn bạn gửi) ...
85
- # Để cho gọn, mình viết tắt, bạn giữ nguyên code UI của bạn nhé
86
- with gr.Column(elem_classes="header-text"):
87
- gr.Markdown("""<div class="project-title">HỆ THỐNG DỊCH VSL DEMO</div>""")
88
-
89
- with gr.Row():
90
- with gr.Column():
91
- with gr.Tabs():
92
- with gr.TabItem("Giọng nói"):
93
- input_audio = gr.Audio(sources=["microphone", "upload"], type="filepath")
94
- mode_audio = gr.State(value="Giọng nói (Microphone/File)")
95
- btn_audio = gr.Button("Xử lý Giọng nói", variant="primary")
96
- with gr.TabItem("Văn bản"):
97
- input_text = gr.Textbox(label="Nhập text")
98
- mode_text = gr.State(value="Văn bản (Nhập tay)")
99
- btn_text = gr.Button("Dịch Văn bản", variant="primary")
100
-
101
- with gr.Column():
102
- output_vi = gr.Textbox(label="Tiếng Việt")
103
- output_gloss = gr.Textbox(label="VSL Gloss")
104
-
105
- btn_audio.click(fn=full_pipeline, inputs=[input_audio, input_text, mode_audio], outputs=[output_vi, output_gloss])
106
- btn_text.click(fn=full_pipeline, inputs=[input_audio, input_text, mode_text], outputs=[output_vi, output_gloss])
107
-
108
- # Chạy app
109
- if __name__ == "__main__":
110
  demo.launch()
 
1
+ import torch
2
+ import gradio as gr
3
+ from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
4
+
5
+ # --- PHẦN 1: CẤU HÌNH & LOAD MODEL ---
6
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
7
+
8
+ # 1. Load PhoWhisper (Nhận dạng giọng nói)
9
+ print("Đang tải model PhoWhisper...")
10
+ asr_pipeline = pipeline(
11
+ "automatic-speech-recognition",
12
+ model="vinai/PhoWhisper-small",
13
+ device=0 if torch.cuda.is_available() else -1
14
+ )
15
+
16
+ # 2. Load Model Dịch (ViT5)
17
+ # LƯU Ý QUAN TRỌNG:
18
+ TRANSLATION_MODEL_PATH = "."
19
+
20
+ print(f"Đang tải model dịch...")
21
+ try:
22
+ trans_tokenizer = AutoTokenizer.from_pretrained(TRANSLATION_MODEL_PATH)
23
+ trans_model = AutoModelForSeq2SeqLM.from_pretrained(TRANSLATION_MODEL_PATH).to(DEVICE)
24
+ print("Load model dịch thành công!")
25
+ except Exception as e:
26
+ print(f"Lỗi load model dịch: {e}")
27
+ trans_model = None
28
+
29
+
30
+ # --- PHẦN 2: CÁC HÀM XỬ LÝ (LOGIC) ---
31
+ def speech_to_text(audio_path):
32
+ if audio_path is None: return ""
33
+ try:
34
+ output = asr_pipeline(audio_path)
35
+ return output['text']
36
+ except Exception as e:
37
+ return f"Lỗi: {str(e)}"
38
+
39
+ def text_to_gloss(vietnamese_text):
40
+ if not vietnamese_text: return ""
41
+ if trans_model is None: return "Lỗi: Chưa load được model dịch."
42
+
43
+ input_text = f"vi: {vietnamese_text}"
44
+ inputs = trans_tokenizer(input_text, return_tensors="pt", max_length=128, truncation=True).to(DEVICE)
45
+
46
+ with torch.no_grad():
47
+ outputs = trans_model.generate(
48
+ inputs["input_ids"],
49
+ max_length=128,
50
+ num_beams=5,
51
+ early_stopping=True
52
+ )
53
+
54
+ gloss_text = trans_tokenizer.decode(outputs[0], skip_special_tokens=True)
55
+ return gloss_text.replace("vsl: ", "") if gloss_text.startswith("vsl: ") else gloss_text
56
+
57
+ def full_pipeline(audio, text_input, mode):
58
+ vietnamese_output = ""
59
+ if mode == "Giọng nói (Microphone/File)" and audio is not None:
60
+ vietnamese_output = speech_to_text(audio)
61
+ elif mode == "Văn bản (Nhập tay)" and text_input:
62
+ vietnamese_output = text_input
63
+ else:
64
+ return "Vui lòng nhập dữ liệu.", ""
65
+
66
+ gloss_output = text_to_gloss(vietnamese_output)
67
+ return vietnamese_output, gloss_output
68
+
69
+
70
+ # --- PHẦN 3: GIAO DIỆN (UI) - ĐOẠN CODE CỦA BẠN ---
71
+ custom_css = """
72
+ .container {max-width: 1200px; margin: auto; padding-top: 20px}
73
+ .header-text {text-align: center; font-family: 'Arial', sans-serif;}
74
+ .uni-name {font-size: 24px; font-weight: bold; color: #003366; margin-bottom: 5px;}
75
+ .faculty-name {font-size: 18px; font-weight: normal; color: #cc0000; margin-bottom: 20px;}
76
+ .project-title {font-size: 28px; font-weight: bold; color: #2c3e50; margin-bottom: 10px; border-bottom: 2px solid #eee; padding-bottom: 10px;}
77
+ .note-text {font-size: 14px; font-style: italic; color: #7f8c8d; margin-top: 20px; border-top: 1px solid #eee; padding-top: 10px;}
78
+ .output-box {border: 1px solid #e0e0e0; background-color: #f9f9f9; border-radius: 8px;}
79
+ """
80
+
81
+ with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
82
+ # ... (Dán phần giao diện của bạn vào đây, y hệt đoạn bạn gửi) ...
83
+ # Để cho gọn, mình viết tắt, bạn giữ nguyên code UI của bạn nhé
84
+ with gr.Column(elem_classes="header-text"):
85
+ gr.Markdown("""<div class="project-title">HỆ THỐNG DỊCH VSL DEMO</div>""")
86
+
87
+ with gr.Row():
88
+ with gr.Column():
89
+ with gr.Tabs():
90
+ with gr.TabItem("Giọng nói"):
91
+ input_audio = gr.Audio(sources=["microphone", "upload"], type="filepath")
92
+ mode_audio = gr.State(value="Giọng nói (Microphone/File)")
93
+ btn_audio = gr.Button("Xử lý Giọng nói", variant="primary")
94
+ with gr.TabItem("Văn bản"):
95
+ input_text = gr.Textbox(label="Nhập text")
96
+ mode_text = gr.State(value="Văn bản (Nhập tay)")
97
+ btn_text = gr.Button("Dịch Văn bản", variant="primary")
98
+
99
+ with gr.Column():
100
+ output_vi = gr.Textbox(label="Tiếng Việt")
101
+ output_gloss = gr.Textbox(label="VSL Gloss")
102
+
103
+ btn_audio.click(fn=full_pipeline, inputs=[input_audio, input_text, mode_audio], outputs=[output_vi, output_gloss])
104
+ btn_text.click(fn=full_pipeline, inputs=[input_audio, input_text, mode_text], outputs=[output_vi, output_gloss])
105
+
106
+ # Chạy app
107
+ if __name__ == "__main__":
 
 
108
  demo.launch()