Files
faster-whisper-n-ionet-llm/handlers/gradioHandler.py
2025-10-10 12:06:00 +03:00

103 lines
5.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from config import LLM_MODELS # Импортируем словарь моделей
import gradio as gr
from config import GEMINI_API_KEY, IO_API_KEY
class GradioHandlers:
def __init__(self, llm_factory, ConvertMdToPdf, FileHandlers, FasterWhisper, GlueAudio):
# Объект для работы с файлами
self.fh = FileHandlers()
self.ga = GlueAudio()
self.ConvertMdToPdf = ConvertMdToPdf()
self.FasterWhisper = FasterWhisper()
self.llm_factory = llm_factory
def handleRecognizeBtn(
<<<<<<< HEAD
self,
audioFiles, model, device, compute_type, beamSize, vadFilter,
minSilenceDurationMs, speechPadMs, temp0, temp1, temp2, wordTimestamps,
noSpeechThreshold, conditionOnPreviousText, filename, outPath
):
try:
audioFile = self.ga.glue(audioFiles, output)
file = self.fh.saveFile(filename, audioFile, outPath)
return self.FasterWhisper.recognize(model, device, compute_type, file, beamSize, vadFilter, minSilenceDurationMs, speechPadMs, temp0, temp1, temp2, wordTimestamps, noSpeechThreshold, conditionOnPreviousText)
except (FileNotFoundError, RuntimeError) as e:
# Если FFmpeg не найден или произошла ошибка, сообщаем пользователю
gr.Warning(str(e))
return "" # Возвращаем пустую строку в текстовое поле
=======
self, audioFiles, model, device, compute_type, beamSize, vadFilter,
minSilenceDurationMs, speechPadMs, temp0, temp1, temp2,
wordTimestamps, noSpeechThreshold, conditionOnPreviousText, filename, outPath
):
try:
glued_audio_path = self.ga.glue(
audio_files=[f.name for f in audioFiles], # Передаем список путей
output_path=outPath,
output_filename=filename
)
except (FileNotFoundError, RuntimeError) as e:
# Если FFmpeg не найден или произошла ошибка, сообщаем пользователю
gr.Warning(str(e))
return "" # Возвращаем пустую строку в текстовое поле
# Передаем путь к склеенному файлу в FasterWhisper
return self.FasterWhisper.recognize(model, device, compute_type, str(glued_audio_path), beamSize, vadFilter, minSilenceDurationMs, speechPadMs, temp0, temp1, temp2, wordTimestamps, noSpeechThreshold, conditionOnPreviousText)
>>>>>>> 1e5105b7d658310c159c65ba318c08522506c3fb
# Функция улучшения текста
def generateByCondition(self, api_key, llm_provider,
llm_model, system_prompt, recognized_text,
llm_temperature, is_pipeline_enabled, trigger,
isSaveFile, filename, filenamePdf, output_path):
try:
# Получаем нужный провайдер через фабрику
provider = self.llm_factory(llm_provider, api_key)
except ValueError as e:
# Если API ключ не предоставлен для нужного провайдера, выводим ошибку
gr.Warning(str(e))
return gr.skip(), gr.skip()
def process():
result, md = provider.generate(llm_model, system_prompt, recognized_text, llm_temperature)
pdf, unicodeText = self.ConvertMdToPdf.convertLatexToText(md)
if isSaveFile:
self.fh.saveFile(filenamePdf, pdf, output_path)
self.fh.saveFile(filename, result, output_path)
return result, unicodeText
if (is_pipeline_enabled and trigger == "change") or (not is_pipeline_enabled and trigger == "click"):
return process()
return gr.skip(), gr.skip()
# НОВАЯ ФУНКЦИЯ для обновления списка моделей
def update_model_dropdown(self, provider):
"""
Вызывается при изменении llmProvider.
Возвращает обновленный компонент Dropdown для моделей.
"""
# Получаем список моделей для выбранного провайдера
models = LLM_MODELS.get(provider, [])
# Выбираем первое значение по умолчанию, если список не пуст
default_value = models[0] if models else None
# Возвращаем обновленный компонент. Используем 'gr' напрямую.
if provider == 'io.net': return gr.update(choices=models, value=default_value), gr.update(label='API key (required for io.net, Gemini)', value=IO_API_KEY, interactive=True)
if provider == 'Gemini': return gr.update(choices=models, value=default_value), gr.update(label='API key (required for Oio.net, Gemini)', value=GEMINI_API_KEY, interactive=True)
if provider == 'gpt4free': return gr.update(choices=models, value=default_value), gr.update(label='API key (required for Oio.net, Gemini)', value="", interactive=True)
# Функция для динамического обновления кнопки
def updateButton(self, isChecked):
if not isChecked:
variant = 'primary'
else:
variant = 'secondary'
return gr.update(interactive=not isChecked, variant=variant)
def updateTextbox(self, isChecked):
return gr.update(visible=isChecked)