File size: 13,253 Bytes
b20e184 517e316 4401426 517e316 ecc62d7 c893f08 51292dd 29dd7fa c3f021a db5b7cc d848284 330c946 74a50ff 2c7b3a3 b81bb3c 51292dd 1c38456 51292dd 7ad4f69 517e316 ed126db 5b21850 c893f08 2122c44 5b21850 c893f08 5b21850 c893f08 51292dd e0bafc9 29dd7fa e0bafc9 ecc62d7 7ad4f69 ecc62d7 517e316 2c7b3a3 517e316 ed126db 517e316 c9bd401 ecc62d7 b81bb3c e87e36e b81bb3c 517e316 791a532 ed126db 2122c44 ed126db 74a50ff 4401426 74a50ff 5b21850 178d499 dc01c0e 178d499 dc01c0e 2122c44 5b21850 2122c44 3506670 7ad4f69 3506670 791a532 475b798 7ad4f69 475b798 67b8349 475b798 67b8349 475b798 5b21850 475b798 5b21850 c893f08 51292dd e0bafc9 67b8349 e0bafc9 74a50ff 330c946 74a50ff 3506670 7ad4f69 3506670 791a532 2c7b3a3 3506670 2c7b3a3 517e316 |
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 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 |
import gradio as gr
from huggingface_hub import InferenceClient
import PyPDF2
from PIL import Image
import cv2
import numpy as np
from pydub import AudioSegment
from langdetect import detect
from rembg import remove
import torch
import torchvision
from torchvision.models.detection import fasterrcnn_resnet50_fpn
from torchvision.transforms import functional as F
import tempfile
import time
import requests
import zipfile
import os
import torchaudio
from transformers import pipeline
from googletrans import Translator
# Инициализация клиента для модели HuggingFaceH4/zephyr-7b-beta
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
# Загрузка предобученной модели для обнаружения объектов
model = fasterrcnn_resnet50_fpn(weights="DEFAULT")
model.eval()
# Функции для обработки данных (остаются без изменений)
def process_pdf(file):
pdf_reader = PyPDF2.PdfReader(file)
text = ""
for page in pdf_reader.pages:
text += page.extract_text()
return text
def process_image(file):
image = Image.open(file)
return f"Изображение: {image.size[0]}x{image.size[1]} пикселей, формат: {image.format}"
def process_video(file):
cap = cv2.VideoCapture(file.name)
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
duration = frame_count / cap.get(cv2.CAP_PROP_FPS)
cap.release()
return f"Видео: длительность {duration:.2f} секунд, {frame_count} кадров"
def process_audio(file):
audio = AudioSegment.from_file(file)
return f"Аудио: длительность {len(audio) / 1000:.2f} секунд, частота {audio.frame_rate} Гц"
def process_txt(file):
with open(file.name, "r", encoding="utf-8") as f:
text = f.read()
return text
# Функция для удаления фона с возможностью выбора фона или цвета
def remove_background(image, background=None, background_color=None):
if image is None:
return "**Ошибка:** Чем я буду удалять, если ты не загрузил изображение?"
# Удаляем фон с изображения
output = remove(image)
# Если выбран цвет фона
if background_color:
background_image = Image.new("RGB", output.size, background_color)
background_image.paste(output, mask=output)
return background_image
# Если загружен фон
if background:
background_image = Image.open(background).resize(output.size)
background_image.paste(output, mask=output)
return background_image
# Если ничего не выбрано, возвращаем изображение без фона
return output
def count_objects(image):
if image is None:
return "Изображение не загружено."
img = Image.open(image.name).convert("RGB")
img_tensor = F.to_tensor(img).unsqueeze(0)
with torch.no_grad():
predictions = model(img_tensor)
num_objects = len(predictions[0]['labels'])
return f"Количество объектов на изображении: {num_objects}"
def convert_image(image, target_format):
if image is None:
return None
img = Image.open(image.name)
with tempfile.NamedTemporaryFile(delete=False, suffix=f".{target_format.lower()}") as tmp_file:
img.save(tmp_file, format=target_format)
return tmp_file.name
def detect_language(text):
try:
return detect(text)
except:
return "en"
def respond(
message,
history: list[tuple[str, str]],
system_message,
max_tokens,
temperature,
top_p,
file=None,
):
if file is not None:
file_type = file.name.split(".")[-1].lower()
if file_type == "pdf":
file_info = process_pdf(file)
elif file_type in ["jpg", "jpeg", "png", "bmp", "gif"]:
file_info = process_image(file)
elif file_type in ["mp4", "avi", "mov"]:
file_info = process_video(file)
elif file_type in ["mp3", "wav", "ogg"]:
file_info = process_audio(file)
elif file_type == "txt":
file_info = process_txt(file)
else:
file_info = "Неизвестный тип файла"
message += f"\n[Пользователь загрузил файл: {file.name}]\n{file_info}"
language = detect_language(message)
if language == "ru":
system_message = "Вы дружелюбный чат-бот, который понимает русский язык."
else:
system_message = "You are a friendly chatbot."
messages = [{"role": "system", "content": system_message}]
for val in history:
if val[0]:
messages.append({"role": "user", "content": val[0]})
if val[1]:
messages.append({"role": "assistant", "content": val[1]})
messages.append({"role": "user", "content": message})
response = ""
for message in client.chat_completion(
messages,
max_tokens=max_tokens,
stream=True,
temperature=temperature,
top_p=top_p,
):
token = message.choices[0].delta.content
response += token
yield response
def reset_chat():
return []
def analyze_txt(file):
if file is None:
return "**Ошибка:** Ты не загрузил текстовый файл, а значит я не буду анализировать пустой файл."
text = process_txt(file)
return f"Содержимое файла:\n{text}"
def resize_image(image, width: int, height: int):
if image is None:
return None
img = Image.open(image.name)
resized_img = img.resize((width, height))
with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp_file:
resized_img.save(tmp_file.name)
return tmp_file.name
def translate_text(text: str, target_language: str):
translator = Translator()
try:
translation = translator.translate(text, dest=target_language)
return translation.text
except Exception as e:
return f"Ошибка перевода: {str(e)}"
# Создание интерфейса
with gr.Blocks() as demo:
# Заголовок с изображением и значками
gr.HTML("""
<div style="text-align: center;">
<img src="https://huggingface.co/spaces/Felguk/Felguk-v0/resolve/main/hd_crop_4c480c6a2c7e176289b0dfcb64a30603_67753ddec8355.png" alt="Felguk Logo" style="width: 300px;">
<div style="margin-top: 10px;">
<a href="https://github.com/Redcorehash">
<img src="https://img.shields.io/badge/GitHub-Repo-blue?style=for-the-badge&logo=github" alt="GitHub">
</a>
<a href="https://huggingface.co/felguk">
<img src="https://img.shields.io/badge/Hugging%20Face-Profile-yellow?style=for-the-badge&logo=huggingface" alt="Hugging Face">
</a>
</div>
</div>
""")
# Felguk News
gr.Markdown("""
## Felguk News
**Последнее обновление:** 2023-10-25
- Добавлена поддержка новых форматов файлов.
- Улучшена производительность обработки изображений.
- Исправлены ошибки в переводе текста.
""")
gr.Markdown("Чат-бот Felguk v0. Отвечает на том же языке, на котором вы написали. Задавайте вопросы и загружайте файлы (PDF, изображения, видео, аудио, txt)!")
# Кнопка "Новый чат"
with gr.Row():
new_chat_button = gr.Button("Новый чат", variant="secondary")
# Felguk Tools: Отдельные инструменты
with gr.Tabs():
# Вкладка Txt Analyzer
with gr.Tab("Анализатор текста"):
gr.Markdown("## Анализатор текста")
txt_file = gr.File(label="Загрузите txt файл", file_types=[".txt"])
txt_output = gr.Textbox(label="Содержимое файла", interactive=False)
analyze_button = gr.Button("Анализировать")
analyze_button.click(fn=analyze_txt, inputs=txt_file, outputs=txt_output)
# Вкладка Remove Background
with gr.Tab("Удаление фона"):
gr.Markdown("## Удаление фона с изображения")
image_input = gr.Image(label="Загрузите изображение", type="pil")
background_input = gr.Image(label="Загрузите фон (опционально)", type="pil")
background_color_input = gr.ColorPicker(label="Выберите цвет фона (опционально)")
remove_bg_button = gr.Button("Удалить фон")
image_output = gr.Image(label="Результат (без фона)", type="pil")
remove_bg_button.click(
fn=remove_background,
inputs=[image_input, background_input, background_color_input],
outputs=image_output
)
# Вкладка Numage
with gr.Tab("Numage"):
gr.Markdown("## Numage: Подсчет объектов на изображении")
numage_input = gr.File(label="Загрузите изображение", file_types=["image"])
numage_output = gr.Textbox(label="Результат", interactive=False)
numage_button = gr.Button("Определить количество объектов")
numage_button.click(fn=count_objects, inputs=numage_input, outputs=numage_output)
# Вкладка ConverjerIMG
with gr.Tab("Конвертер изображений"):
gr.Markdown("## Конвертер изображений")
img_input = gr.File(label="Загрузите изображение", file_types=["image"])
img_format = gr.Dropdown(
choices=["JPEG", "PNG", "BMP", "GIF", "TIFF"],
label="Выберите формат для конвертации",
value="JPEG"
)
img_output = gr.File(label="Результат конвертации")
convert_button = gr.Button("Конвертировать")
convert_button.click(fn=convert_image, inputs=[img_input, img_format], outputs=img_output)
# Вкладка Felguk-ImageResizer
with gr.Tab("Felguk-ImageResizer"):
gr.Markdown("## Felguk-ImageResizer: Изменение размера изображения")
image_input = gr.File(label="Загрузите изображение", file_types=["image"])
width_input = gr.Number(label="Ширина", value=300)
height_input = gr.Number(label="Высота", value=300)
resize_button = gr.Button("Изменить размер")
resized_image_output = gr.Image(label="Результат", type="filepath")
resize_button.click(fn=resize_image, inputs=[image_input, width_input, height_input], outputs=resized_image_output)
# Вкладка Felguk-TextTranslator
with gr.Tab("Felguk-TextTranslator"):
gr.Markdown("## Felguk-TextTranslator: Перевод текста")
text_input = gr.Textbox(label="Введите текст для перевода", lines=5)
target_language_input = gr.Dropdown(
choices=["en", "ru", "es", "fr", "de"],
label="Выберите язык перевода",
value="en"
)
translate_button = gr.Button("Перевести")
translated_text_output = gr.Textbox(label="Результат", interactive=False)
translate_button.click(fn=translate_text, inputs=[text_input, target_language_input], outputs=translated_text_output)
# Интерфейс чата
chat_interface = gr.ChatInterface(
respond,
additional_inputs=[
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
gr.Slider(
minimum=0.1,
maximum=1.0,
value=0.95,
step=0.05,
label="Top-p (nucleus sampling)",
),
gr.File(label="Загрузите файл (опционально)"),
],
)
# Привязка кнопки "Новый чат" к функции сброса истории
new_chat_button.click(fn=reset_chat, outputs=chat_interface.chatbot)
# Запуск интерфейса
if __name__ == "__main__":
demo.launch() |