Audio-to-LaTeX / app.py
Hyeonsieun's picture
Update app.py
87ce87a verified
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()