add Custom provider

This commit is contained in:
2025-12-14 06:31:00 +03:00
parent 1e5105b7d6
commit 9bf9d8a55d
10 changed files with 197 additions and 104 deletions

View File

@@ -1,50 +1,52 @@
from config import LLM_MODELS # Импортируем словарь моделей
from config import LLM_MODELS, GEMINI_API_KEY, IO_API_KEY
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 # Сохраняем фабрику
self.llm_factory = llm_factory
def handleRecognizeBtn(
self, audioFiles, model, device, compute_type, beamSize, vadFilter,
def handleRecognizeBtn(self, audioFiles, model, device, compute_type, beamSize, vadFilter,
minSilenceDurationMs, speechPadMs, temp0, temp1, temp2,
wordTimestamps, noSpeechThreshold, conditionOnPreviousText, filename, outPath
):
wordTimestamps, noSpeechThreshold, conditionOnPreviousText, filename, outPath):
try:
glued_audio_path = self.ga.glue(
audio_files=[f.name for f in audioFiles], # Передаем список путей
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 "" # Возвращаем пустую строку в текстовое поле
return ""
# Передаем путь к склеенному файлу в FasterWhisper
return self.FasterWhisper.recognize(model, device, compute_type, str(glued_audio_path), beamSize, vadFilter, minSilenceDurationMs, speechPadMs, temp0, temp1, temp2, wordTimestamps, noSpeechThreshold, conditionOnPreviousText)
# Функция улучшения текста
# Добавил аргумент custom_base_url в конец
def generateByCondition(self, api_key, llm_provider,
llm_model, system_prompt, recognized_text,
llm_temperature, is_pipeline_enabled, trigger,
isSaveFile, filename, filenamePdf, output_path):
isSaveFile, filename, filenamePdf, output_path, custom_base_url):
try:
# Получаем нужный провайдер через фабрику
provider = self.llm_factory(llm_provider, api_key)
if llm_provider == "Custom":
# Передаем base_url только для Custom
provider = self.llm_factory(llm_provider, api_key, base_url=custom_base_url)
else:
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)
# Добавлена обработка ошибок генерации
try:
result, md = provider.generate(llm_model, system_prompt, recognized_text, llm_temperature)
except Exception as e:
raise gr.Error(f"Ошибка генерации LLM: {e}")
pdf, unicodeText = self.ConvertMdToPdf.convertLatexToText(md)
if isSaveFile:
self.fh.saveFile(filenamePdf, pdf, output_path)
@@ -56,30 +58,30 @@ class GradioHandlers:
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)
# Обновляем список моделей и настройки поля API Key
if provider == 'io.net':
return gr.update(choices=models, value=default_value), gr.update(label='API key', value=IO_API_KEY, interactive=True, visible=True)
if provider == 'Gemini':
return gr.update(choices=models, value=default_value), gr.update(label='API key', value=GEMINI_API_KEY, interactive=True, visible=True)
if provider == 'gpt4free':
return gr.update(choices=models, value=default_value), gr.update(label='API key (not required)', value="", interactive=False, visible=True)
if provider == "Custom":
return gr.update(choices=models, value=default_value), gr.update(label='API key (optional)', value="", interactive=True, visible=True) # Для Custom ключ может понадобиться
# Функция для динамического обновления кнопки
def updateButton(self, isChecked):
if not isChecked:
variant = 'primary'
else:
variant = 'secondary'
variant = 'secondary' if isChecked else 'primary'
return gr.update(interactive=not isChecked, variant=variant)
def toggle_custom_url(self, provider):
"""Показывает поле Base URL только если выбран Custom"""
return gr.update(visible=(provider == 'Custom'))
def update_custom_url(self, base_url):
return None
def updateTextbox(self, isChecked):
return gr.update(visible=isChecked)

View File

@@ -0,0 +1,21 @@
import os
from PIL import Image, ExifTags
import subprocess
import json
from datetime import datetime
class MetadataHandler:
def get_image_timestamp(self, image_path: str) -> datetime | None:
"""Извлекает метку времени из метаданных изображения, если она доступна."""
try:
image = Image.open(image_path)
exif_data = image._getexif()
if exif_data:
for tag, value in exif_data.items():
decoded_tag = ExifTags.TAGS.get(tag, tag)
if decoded_tag == 'DateTimeOriginal':
return value
return None
except Exception as e:
print(f"Error extracting metadata from image: {e}")
return None