File size: 5,399 Bytes
afedaa3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87ce87a
afedaa3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import torch

import gradio as gr
from transformers import pipeline
from transformers import T5ForConditionalGeneration, T5Tokenizer

import re
import os
import json
import requests
import whisper
from yt_dlp import YoutubeDL

import matplotlib as plt

#whisper_model = whisper.load_model('small')

path = "Hyeonsieun/NTtoGT_7epoch"
tokenizer = T5Tokenizer.from_pretrained(path)
model = T5ForConditionalGeneration.from_pretrained(path)


MODEL_NAME = "openai/whisper-large-v2"
BATCH_SIZE = 8
#FILE_LIMIT_MB = 1000

pipe = pipeline(
    task="automatic-speech-recognition",
    model=MODEL_NAME,
    chunk_length_s=30,
)


def transcribe(inputs):
    if inputs is None:
        raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")

    text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": "transcribe"}, return_timestamps=True)["text"]
    return  text

def remove_spaces_within_dollar(text):
    # ๋‹ฌ๋Ÿฌ ๊ธฐํ˜ธ๋กœ ๋‘˜๋Ÿฌ์‹ธ์ธ ๋ถ€๋ถ„์—์„œ ์ŠคํŽ˜์ด์Šค ์ œ๊ฑฐ
    # ์ •๊ทœ ํ‘œํ˜„์‹: \$.*?\$ ๋Š” '$'๋กœ ์‹œ์ž‘ํ•ด์„œ '$'๋กœ ๋๋‚˜๋Š” ์ตœ์†Œํ•œ์˜ ๋ฌธ์ž์—ด์„ ์ฐพ์Œ (non-greedy)
    # re.sub์˜ repl ํŒŒ๋ผ๋ฏธํ„ฐ์— ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋งค์น˜๋œ ๋ถ€๋ถ„์—์„œ๋งŒ ๋ณ€๊ฒฝ์„ ์ ์šฉ
    result = re.sub(r'\$(.*?)\$', lambda match: match.group(0).replace(' ', ''), text)
    return result


def audio_correction(file):
    ASR_result = transcribe(file)
    text_list = split_text_complex_rules_with_warning(ASR_result)
    whole_text = ''
    for text in text_list:
        input_text = f"translate the text pronouncing the formula to a LaTeX equation: {text}"
        inputs = tokenizer.encode(
            input_text,
            return_tensors='pt',
            max_length=325,
            padding='max_length',
            truncation=True
        )
        # Get correct sentence ids.
        corrected_ids = model.generate(
            inputs,
            max_length=325,
            num_beams=5, # `num_beams=1` indicated temperature sampling.
            early_stopping=True
        )
        # Decode.
        corrected_sentence = tokenizer.decode(
            corrected_ids[0],
            skip_special_tokens=False
        )
        whole_text += corrected_sentence

    return remove_spaces_within_dollar(whole_text)[5:-4]

def youtubeASR(link):
    # ์œ ํŠœ๋ธŒ์˜ ์Œ์„ฑ๋งŒ ๋‹ค์šด๋กœ๋“œํ•  ์ž„์‹œ ํŒŒ์ผ๋ช…
    out_fn = 'temp1.mp3'

    ydl_opts = {
        'format': 'bestaudio/best', # Audio๋งŒ ๋‹ค์šด๋กœ๋“œ
        'outtmpl': out_fn,          # ์ง€์ •ํ•œ ํŒŒ์ผ๋ช…์œผ๋กœ ์ €์žฅ
    }

    with YoutubeDL(ydl_opts) as ydl:
        ydl.download([link])

    result = pipe(out_fn, batch_size=BATCH_SIZE, generate_kwargs={"task": "transcribe"}, return_timestamps=True)["text"]      # Youtube์—์„œ ๋ฐ›์€ ์Œ์„ฑ ํŒŒ์ผ(out_fn)์„ ๋ฐ›์•„์“ฐ๊ธฐ
    script = result['text']            # ๋ฐ›์•„์“ฐ๊ธฐ ํ•œ ๋‚ด์šฉ ์ €์žฅ
    return script

def split_text_complex_rules_with_warning(text):
    # ์ฝค๋งˆ๋ฅผ ์ œ์™ธํ•œ ๊ตฌ๋‘์ ์œผ๋กœ ๋ฌธ์žฅ ๋ถ„๋ฆฌ
    parts = re.split(r'(?<=[.?!])\s+', text)

    result = []
    warnings = []  # ๊ฒฝ๊ณ  ๋ฉ”์‹œ์ง€๋ฅผ ์ €์žฅํ•  ๋ฆฌ์ŠคํŠธ
    for part in parts:
        # ๊ฐ ๋ถ€๋ถ„์˜ ๊ธธ์ด๊ฐ€ 256์ž๋ฅผ ์ดˆ๊ณผํ•˜๋Š” ๊ฒฝ์šฐ ์ฝค๋งˆ๋กœ ์ถ”๊ฐ€ ๋ถ„๋ฆฌ
        if len(part) > 256:
            subparts = re.split(r',\s*', part)
            for subpart in subparts:
                # ๋นˆ ๋ฌธ์ž์—ด ์ œ๊ฑฐ ๋ฐ ๊ธธ์ด๊ฐ€ 256์ž ์ดํ•˜์ธ ๊ฒฝ์šฐ๋งŒ ๊ฒฐ๊ณผ ๋ฆฌ์ŠคํŠธ์— ์ถ”๊ฐ€
                trimmed_subpart = subpart.strip()
                if trimmed_subpart and len(trimmed_subpart) <= 256:
                    result.append(trimmed_subpart)
                else:
                    # ๊ธธ์ด๊ฐ€ 256์ž๋ฅผ ์ดˆ๊ณผํ•˜๋Š” ๊ฒฝ์šฐ ๊ฒฝ๊ณ  ๋ฉ”์‹œ์ง€ ์ถ”๊ฐ€
                    warnings.append(f"๋ฌธ์žฅ ๊ธธ์ด๊ฐ€ 256์ž๋ฅผ ์ดˆ๊ณผํ•ฉ๋‹ˆ๋‹ค: {trimmed_subpart[:50]}... (๊ธธ์ด: {len(trimmed_subpart)})")
        else:
            # ๊ธธ์ด๊ฐ€ 256์ž ์ดํ•˜์ธ ๊ฒฝ์šฐ ๋ฐ”๋กœ ๊ฒฐ๊ณผ ๋ฆฌ์ŠคํŠธ์— ์ถ”๊ฐ€
            result.append(part.strip())
    warnings = 0

    return result


def youtube_correction(link):
    ASR_result = youtubeASR(link)
    text_list = split_text_complex_rules_with_warning(ASR_result)
    whole_text = ''
    for text in text_list:
        input_text = f"translate the text pronouncing the formula to a LaTeX equation: {text}"
        inputs = tokenizer.encode(
            input_text,
            return_tensors='pt',
            max_length=325,
            padding='max_length',
            truncation=True
        )
        # Get correct sentence ids.
        corrected_ids = model.generate(
            inputs,
            max_length=325,
            num_beams=5, # `num_beams=1` indicated temperature sampling.
            early_stopping=True
        )
        # Decode.
        corrected_sentence = tokenizer.decode(
            corrected_ids[0],
            skip_special_tokens=False
        )
        whole_text += corrected_sentence

    return remove_spaces_within_dollar(whole_text)[5:-4]


demo = gr.Blocks()

file_transcribe = gr.Interface(
    fn=audio_correction,
    inputs=gr.components.Audio(sources="upload", type="filepath"),
    outputs="text"
    )

yt_transcribe = gr.Interface(
    fn=youtube_correction,
    inputs="text",
    outputs="text"
    )

with demo:
    gr.TabbedInterface([file_transcribe, yt_transcribe], ["Audio file", "YouTube"])

demo.launch()