Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,8 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from transformers import pipeline
|
| 3 |
-
from diffusers import
|
| 4 |
import torch
|
| 5 |
from PIL import Image
|
| 6 |
-
import requests
|
| 7 |
-
from io import BytesIO
|
| 8 |
|
| 9 |
# Загружаем модели для анализа тональности, суммаризации текста, генерации подписей к изображениям, ответов на вопросы, перевода текста, определения эмоций, автодополнения кода, определения фейковых новостей, NER, классификации изображений, генерации кода и исправления кода
|
| 10 |
sentiment_pipeline = pipeline("sentiment-analysis")
|
|
@@ -20,71 +18,54 @@ image_classification_pipeline = pipeline("image-classification", model="google/v
|
|
| 20 |
code_generation_pipeline = pipeline("text-generation", model="deepseek-ai/deepseek-coder-1.3b-instruct")
|
| 21 |
code_fix_pipeline = pipeline("text-generation", model="deepseek-ai/deepseek-coder-1.3b-instruct")
|
| 22 |
|
| 23 |
-
#
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
else
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
#
|
| 32 |
-
def
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
model=None,
|
| 38 |
-
tile=0,
|
| 39 |
-
tile_pad=10,
|
| 40 |
-
pre_pad=0,
|
| 41 |
-
half=False,
|
| 42 |
-
)
|
| 43 |
-
return model
|
| 44 |
-
|
| 45 |
-
esrgan_model = load_esrgan_model()
|
| 46 |
|
| 47 |
-
#
|
| 48 |
def analyze_sentiment(text):
|
| 49 |
result = sentiment_pipeline(text)[0]
|
| 50 |
return f"Label: {result['label']}, Confidence: {result['score']:.4f}"
|
| 51 |
|
| 52 |
-
# Функция для суммаризации текста
|
| 53 |
def summarize_text(text):
|
| 54 |
result = summarization_pipeline(text, max_length=50, min_length=25, do_sample=False)
|
| 55 |
return result[0]['summary_text']
|
| 56 |
|
| 57 |
-
# Функция для генерации подписи к изображению
|
| 58 |
def generate_caption(image):
|
| 59 |
result = image_captioning_pipeline(image)
|
| 60 |
return result[0]['generated_text']
|
| 61 |
|
| 62 |
-
# Функция для ответов на вопросы
|
| 63 |
def answer_question(context, question):
|
| 64 |
result = qa_pipeline(question=question, context=context)
|
| 65 |
return f"Answer: {result['answer']}, Confidence: {result['score']:.4f}"
|
| 66 |
|
| 67 |
-
# Функция для перевода текста
|
| 68 |
def translate_text(text):
|
| 69 |
result = translation_pipeline(text)
|
| 70 |
return result[0]['translation_text']
|
| 71 |
|
| 72 |
-
# Функция для определения эмоций
|
| 73 |
def detect_emotion(text):
|
| 74 |
result = emotion_pipeline(text)[0]
|
| 75 |
return f"Emotion: {result['label']}, Confidence: {result['score']:.4f}"
|
| 76 |
|
| 77 |
-
# Функция для автодополнения кода
|
| 78 |
def complete_code(code):
|
| 79 |
result = code_completion_pipeline(code, max_length=50, num_return_sequences=1)
|
| 80 |
return result[0]['generated_text']
|
| 81 |
|
| 82 |
-
# Функция для определения фейковых новостей
|
| 83 |
def detect_fake_news(text):
|
| 84 |
result = fake_news_pipeline(text)[0]
|
| 85 |
return f"Label: {result['label']}, Confidence: {result['score']:.4f}"
|
| 86 |
|
| 87 |
-
# Функция для распознавания именованных сущностей (NER)
|
| 88 |
def recognize_entities(text):
|
| 89 |
result = ner_pipeline(text)
|
| 90 |
entities = []
|
|
@@ -92,7 +73,6 @@ def recognize_entities(text):
|
|
| 92 |
entities.append(f"Entity: {entity['word']}, Label: {entity['entity_group']}, Confidence: {entity['score']:.4f}")
|
| 93 |
return "\n".join(entities)
|
| 94 |
|
| 95 |
-
# Функция для классификации изображений
|
| 96 |
def classify_image(image):
|
| 97 |
result = image_classification_pipeline(image)
|
| 98 |
classifications = []
|
|
@@ -100,12 +80,10 @@ def classify_image(image):
|
|
| 100 |
classifications.append(f"Label: {item['label']}, Confidence: {item['score']:.4f}")
|
| 101 |
return "\n".join(classifications)
|
| 102 |
|
| 103 |
-
# Функция для генерации кода по запросу
|
| 104 |
def generate_code(prompt):
|
| 105 |
result = code_generation_pipeline(prompt, max_length=100, num_return_sequences=1)
|
| 106 |
return result[0]['generated_text']
|
| 107 |
|
| 108 |
-
# Функция для исправления кода
|
| 109 |
def fix_code(error, problem, solution, example):
|
| 110 |
prompt = f"""
|
| 111 |
**Ошибка:** {error}
|
|
@@ -116,107 +94,6 @@ def fix_code(error, problem, solution, example):
|
|
| 116 |
result = code_fix_pipeline(prompt, max_length=200, num_return_sequences=1)
|
| 117 |
return result[0]['generated_text']
|
| 118 |
|
| 119 |
-
# Функция для расширения изображений (Flux Extend Image)
|
| 120 |
-
def extend_image(image):
|
| 121 |
-
# Преобразуем изображение в формат, подходящий для модели
|
| 122 |
-
img = Image.open(image).convert("RGB")
|
| 123 |
-
output, _ = esrgan_model.enhance(img, outscale=4)
|
| 124 |
-
return output
|
| 125 |
-
|
| 126 |
-
# Функция для генерации изображений (Image Generation)
|
| 127 |
-
def generate_image(prompt):
|
| 128 |
-
with torch.autocast("cuda"):
|
| 129 |
-
image = image_generation_pipeline(prompt).images[0]
|
| 130 |
-
return image
|
| 131 |
-
|
| 132 |
-
# Примеры текстов для анализа тональности
|
| 133 |
-
sentiment_examples = [
|
| 134 |
-
"I love programming, it's so much fun!",
|
| 135 |
-
"This movie was terrible, I hated it.",
|
| 136 |
-
"The weather is nice today.",
|
| 137 |
-
"I feel so frustrated with this project.",
|
| 138 |
-
"Gradio is an amazing tool for building ML demos!"
|
| 139 |
-
]
|
| 140 |
-
|
| 141 |
-
# Примеры текстов для суммаризации
|
| 142 |
-
summarization_examples = [
|
| 143 |
-
"Gradio is a powerful tool for building machine learning demos. It allows developers to quickly create interactive interfaces for their models.",
|
| 144 |
-
"The weather today is sunny with a slight breeze. It's a perfect day to go outside and enjoy nature.",
|
| 145 |
-
"Artificial intelligence is transforming industries by automating tasks and providing insights from large datasets."
|
| 146 |
-
]
|
| 147 |
-
|
| 148 |
-
# Примеры изображений для генерации подписей
|
| 149 |
-
image_examples = [
|
| 150 |
-
"https://a.d-cd.net/b977306s-1920.jpg", # Пример 1
|
| 151 |
-
"https://i.pinimg.com/originals/ba/bd/6d/babd6d37eb2dd965c7f1dfb516d54094.jpg", # Пример 2
|
| 152 |
-
"https://get.wallhere.com/photo/sea-bay-water-beach-coast-swimming-pool-resort-island-lagoon-Caribbean-vacation-estate-leisure-ocean-tropics-2560x1440-px-geographical-feature-atoll-554636.jpg" # Пример 3
|
| 153 |
-
]
|
| 154 |
-
|
| 155 |
-
# Примеры для ответов на вопросы
|
| 156 |
-
qa_examples = [
|
| 157 |
-
["Gradio is a Python library for building machine learning demos. It allows developers to quickly create interactive interfaces for their models.", "What is Gradio?"],
|
| 158 |
-
["The weather today is sunny with a slight breeze. It's a perfect day to go outside and enjoy nature.", "What is the weather like today?"],
|
| 159 |
-
["Artificial intelligence is transforming industries by automating tasks and providing insights from large datasets.", "How is AI transforming industries?"]
|
| 160 |
-
]
|
| 161 |
-
|
| 162 |
-
# Примеры текстов для перевода
|
| 163 |
-
translation_examples = [
|
| 164 |
-
"Hello, how are you?",
|
| 165 |
-
"I love machine learning and artificial intelligence.",
|
| 166 |
-
"The weather is beautiful today."
|
| 167 |
-
]
|
| 168 |
-
|
| 169 |
-
# Примеры текстов для определения эмоций
|
| 170 |
-
emotion_examples = [
|
| 171 |
-
"I am so happy today!",
|
| 172 |
-
"I feel really sad about what happened.",
|
| 173 |
-
"This situation makes me angry.",
|
| 174 |
-
"I am scared of the dark.",
|
| 175 |
-
"I am surprised by the results."
|
| 176 |
-
]
|
| 177 |
-
|
| 178 |
-
# Примеры кода для автодополнения
|
| 179 |
-
code_examples = [
|
| 180 |
-
"def factorial(n):",
|
| 181 |
-
"import numpy as np",
|
| 182 |
-
"for i in range(10):"
|
| 183 |
-
]
|
| 184 |
-
|
| 185 |
-
# Примеры текстов для определения фейковых новостей
|
| 186 |
-
fake_news_examples = [
|
| 187 |
-
"A new study shows that eating chocolate every day can make you live longer.",
|
| 188 |
-
"The government has secretly been working on time travel technology for decades.",
|
| 189 |
-
"Scientists have discovered a new planet in our solar system that is inhabited by aliens."
|
| 190 |
-
]
|
| 191 |
-
|
| 192 |
-
# Примеры текстов для распознавания именованных сущностей (NER)
|
| 193 |
-
ner_examples = [
|
| 194 |
-
"My name is John Doe and I live in New York.",
|
| 195 |
-
"Apple is looking at buying a startup in the UK for $1 billion.",
|
| 196 |
-
"Elon Musk is the CEO of Tesla and SpaceX."
|
| 197 |
-
]
|
| 198 |
-
|
| 199 |
-
# Примеры изображений для классификации
|
| 200 |
-
classification_examples = [
|
| 201 |
-
"https://a.d-cd.net/b977306s-1920.jpg", # Пример 1
|
| 202 |
-
"https://i.pinimg.com/originals/ba/bd/6d/babd6d37eb2dd965c7f1dfb516d54094.jpg", # Пример 2
|
| 203 |
-
"https://get.wallhere.com/photo/sea-bay-water-beach-coast-swimming-pool-resort-island-lagoon-Caribbean-vacation-estate-leisure-ocean-tropics-2560x1440-px-geographical-feature-atoll-554636.jpg" # Пример 3
|
| 204 |
-
]
|
| 205 |
-
|
| 206 |
-
# Примеры запросов для генерации кода
|
| 207 |
-
code_generation_examples = [
|
| 208 |
-
"Write a Python function to calculate the factorial of a number.",
|
| 209 |
-
"Create a JavaScript function to reverse a string.",
|
| 210 |
-
"Generate a SQL query to find all users older than 30."
|
| 211 |
-
]
|
| 212 |
-
|
| 213 |
-
# Примеры для исправления кода
|
| 214 |
-
code_fix_examples = [
|
| 215 |
-
["SyntaxError: invalid syntax", "Missing colon at the end of the if statement", "Add a colon at the end of the if statement", "if x == 5\n print('Hello')"],
|
| 216 |
-
["NameError: name 'x' is not defined", "Variable 'x' is not defined before use", "Define the variable 'x' before using it", "print(x)\nx = 10"],
|
| 217 |
-
["IndentationError: unexpected indent", "Incorrect indentation in the code", "Fix the indentation to match the correct level", "def foo():\n print('Hello')\n print('World')"]
|
| 218 |
-
]
|
| 219 |
-
|
| 220 |
# Создаем интерфейс Gradio с вкладками
|
| 221 |
with gr.Blocks() as demo:
|
| 222 |
with gr.Tab("Sentiment Analysis"):
|
|
@@ -226,7 +103,11 @@ with gr.Blocks() as demo:
|
|
| 226 |
outputs="text",
|
| 227 |
title="Анализ тональности текста",
|
| 228 |
description="Введите текст, чтобы определить его тональность.",
|
| 229 |
-
examples=
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
examples_per_page=3
|
| 231 |
)
|
| 232 |
with gr.Tab("Text Summarization"):
|
|
@@ -236,7 +117,10 @@ with gr.Blocks() as demo:
|
|
| 236 |
outputs="text",
|
| 237 |
title="Суммаризация текста",
|
| 238 |
description="Введите текст, чтобы получить его краткое содержание.",
|
| 239 |
-
examples=
|
|
|
|
|
|
|
|
|
|
| 240 |
examples_per_page=2
|
| 241 |
)
|
| 242 |
with gr.Tab("Image Captioning"):
|
|
@@ -246,7 +130,10 @@ with gr.Blocks() as demo:
|
|
| 246 |
outputs="text",
|
| 247 |
title="Генерация подписи к изображению",
|
| 248 |
description="Загрузите изображение, чтобы сгенерировать его описание.",
|
| 249 |
-
examples=
|
|
|
|
|
|
|
|
|
|
| 250 |
examples_per_page=2
|
| 251 |
)
|
| 252 |
with gr.Tab("Question Answering"):
|
|
@@ -259,7 +146,10 @@ with gr.Blocks() as demo:
|
|
| 259 |
outputs="text",
|
| 260 |
title="Ответы на вопросы",
|
| 261 |
description="Введите контекст и вопрос, чтобы получить ответ.",
|
| 262 |
-
examples=
|
|
|
|
|
|
|
|
|
|
| 263 |
examples_per_page=2
|
| 264 |
)
|
| 265 |
with gr.Tab("Language Translation"):
|
|
@@ -269,7 +159,10 @@ with gr.Blocks() as demo:
|
|
| 269 |
outputs="text",
|
| 270 |
title="Перевод текста (английский → русский)",
|
| 271 |
description="Введите текст на английском, чтобы перевести его на русский.",
|
| 272 |
-
examples=
|
|
|
|
|
|
|
|
|
|
| 273 |
examples_per_page=2
|
| 274 |
)
|
| 275 |
with gr.Tab("Emotion Detection"):
|
|
@@ -279,7 +172,10 @@ with gr.Blocks() as demo:
|
|
| 279 |
outputs="text",
|
| 280 |
title="Определение эмоций",
|
| 281 |
description="Введите текст, чтобы определить эмоцию.",
|
| 282 |
-
examples=
|
|
|
|
|
|
|
|
|
|
| 283 |
examples_per_page=2
|
| 284 |
)
|
| 285 |
with gr.Tab("Code Completion"):
|
|
@@ -289,7 +185,10 @@ with gr.Blocks() as demo:
|
|
| 289 |
outputs="text",
|
| 290 |
title="Автодополнение кода",
|
| 291 |
description="Введите начало кода, чтобы получить его продолжение.",
|
| 292 |
-
examples=
|
|
|
|
|
|
|
|
|
|
| 293 |
examples_per_page=2
|
| 294 |
)
|
| 295 |
with gr.Tab("Fake News Detection"):
|
|
@@ -299,7 +198,10 @@ with gr.Blocks() as demo:
|
|
| 299 |
outputs="text",
|
| 300 |
title="Определение фейковых новостей",
|
| 301 |
description="Введите текст новости, чтобы определить, является ли она фейковой.",
|
| 302 |
-
examples=
|
|
|
|
|
|
|
|
|
|
| 303 |
examples_per_page=2
|
| 304 |
)
|
| 305 |
with gr.Tab("Named Entity Recognition (NER)"):
|
|
@@ -309,7 +211,10 @@ with gr.Blocks() as demo:
|
|
| 309 |
outputs="text",
|
| 310 |
title="Распознавание именованных сущностей (NER)",
|
| 311 |
description="Введите текст, чтобы извлечь из него именованные сущности.",
|
| 312 |
-
examples=
|
|
|
|
|
|
|
|
|
|
| 313 |
examples_per_page=2
|
| 314 |
)
|
| 315 |
with gr.Tab("Image Classification"):
|
|
@@ -319,7 +224,10 @@ with gr.Blocks() as demo:
|
|
| 319 |
outputs="text",
|
| 320 |
title="Классификация изображений",
|
| 321 |
description="Загрузите изображение, чтобы классифицировать его.",
|
| 322 |
-
examples=
|
|
|
|
|
|
|
|
|
|
| 323 |
examples_per_page=2
|
| 324 |
)
|
| 325 |
with gr.Tab("Code Generation"):
|
|
@@ -329,7 +237,10 @@ with gr.Blocks() as demo:
|
|
| 329 |
outputs="text",
|
| 330 |
title="Генерация кода по запросу",
|
| 331 |
description="Введите текстовый запрос, чтобы сгенерировать код.",
|
| 332 |
-
examples=
|
|
|
|
|
|
|
|
|
|
| 333 |
examples_per_page=2
|
| 334 |
)
|
| 335 |
with gr.Tab("Code Fix"):
|
|
@@ -344,26 +255,19 @@ with gr.Blocks() as demo:
|
|
| 344 |
outputs="text",
|
| 345 |
title="Исправление кода",
|
| 346 |
description="Введите ошибку, проблему, решение и пример, чтобы получить исправленный код.",
|
| 347 |
-
examples=
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
gr.Interface(
|
| 352 |
-
fn=extend_image,
|
| 353 |
-
inputs=gr.Image(type="pil", label="Загрузите изображение"),
|
| 354 |
-
outputs=gr.Image(type="pil", label="Расширенное изображение"),
|
| 355 |
-
title="Расширение изображений (Flux Extend Image)",
|
| 356 |
-
description="Загрузите изображение, чтобы увеличить его разрешение.",
|
| 357 |
-
examples=image_examples,
|
| 358 |
examples_per_page=2
|
| 359 |
)
|
| 360 |
-
with gr.Tab("Image Generation"):
|
| 361 |
gr.Interface(
|
| 362 |
-
fn=
|
| 363 |
inputs=gr.Textbox(lines=2, placeholder="Введите текстовый запрос..."),
|
| 364 |
outputs=gr.Image(type="pil", label="Сгенерированное изображение"),
|
| 365 |
-
title="Генерация изображений (
|
| 366 |
-
description="Введите текстовый запрос, чтобы сгенерировать
|
| 367 |
examples=[
|
| 368 |
"A futuristic cityscape at night",
|
| 369 |
"A beautiful landscape with mountains and a lake",
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from transformers import pipeline
|
| 3 |
+
from diffusers import DiffusionPipeline # Для Flux
|
| 4 |
import torch
|
| 5 |
from PIL import Image
|
|
|
|
|
|
|
| 6 |
|
| 7 |
# Загружаем модели для анализа тональности, суммаризации текста, генерации подписей к изображениям, ответов на вопросы, перевода текста, определения эмоций, автодополнения кода, определения фейковых новостей, NER, классификации изображений, генерации кода и исправления кода
|
| 8 |
sentiment_pipeline = pipeline("sentiment-analysis")
|
|
|
|
| 18 |
code_generation_pipeline = pipeline("text-generation", model="deepseek-ai/deepseek-coder-1.3b-instruct")
|
| 19 |
code_fix_pipeline = pipeline("text-generation", model="deepseek-ai/deepseek-coder-1.3b-instruct")
|
| 20 |
|
| 21 |
+
# Загрузка модели Flux
|
| 22 |
+
def load_flux_model():
|
| 23 |
+
model_id = "black-forest-labs/flux-1.1-dev" # Замените на правильный путь к модели
|
| 24 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 25 |
+
pipe = DiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16 if device == "cuda" else torch.float32)
|
| 26 |
+
pipe = pipe.to(device)
|
| 27 |
+
return pipe
|
| 28 |
+
|
| 29 |
+
# Функция для генерации изображений с помощью Flux
|
| 30 |
+
def generate_image_flux(prompt):
|
| 31 |
+
pipe = load_flux_model()
|
| 32 |
+
with torch.autocast("cuda" if torch.cuda.is_available() else "cpu"):
|
| 33 |
+
image = pipe(prompt).images[0]
|
| 34 |
+
return image
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
+
# Остальные функции (analyze_sentiment, summarize_text, и т.д.) остаются без изменений
|
| 37 |
def analyze_sentiment(text):
|
| 38 |
result = sentiment_pipeline(text)[0]
|
| 39 |
return f"Label: {result['label']}, Confidence: {result['score']:.4f}"
|
| 40 |
|
|
|
|
| 41 |
def summarize_text(text):
|
| 42 |
result = summarization_pipeline(text, max_length=50, min_length=25, do_sample=False)
|
| 43 |
return result[0]['summary_text']
|
| 44 |
|
|
|
|
| 45 |
def generate_caption(image):
|
| 46 |
result = image_captioning_pipeline(image)
|
| 47 |
return result[0]['generated_text']
|
| 48 |
|
|
|
|
| 49 |
def answer_question(context, question):
|
| 50 |
result = qa_pipeline(question=question, context=context)
|
| 51 |
return f"Answer: {result['answer']}, Confidence: {result['score']:.4f}"
|
| 52 |
|
|
|
|
| 53 |
def translate_text(text):
|
| 54 |
result = translation_pipeline(text)
|
| 55 |
return result[0]['translation_text']
|
| 56 |
|
|
|
|
| 57 |
def detect_emotion(text):
|
| 58 |
result = emotion_pipeline(text)[0]
|
| 59 |
return f"Emotion: {result['label']}, Confidence: {result['score']:.4f}"
|
| 60 |
|
|
|
|
| 61 |
def complete_code(code):
|
| 62 |
result = code_completion_pipeline(code, max_length=50, num_return_sequences=1)
|
| 63 |
return result[0]['generated_text']
|
| 64 |
|
|
|
|
| 65 |
def detect_fake_news(text):
|
| 66 |
result = fake_news_pipeline(text)[0]
|
| 67 |
return f"Label: {result['label']}, Confidence: {result['score']:.4f}"
|
| 68 |
|
|
|
|
| 69 |
def recognize_entities(text):
|
| 70 |
result = ner_pipeline(text)
|
| 71 |
entities = []
|
|
|
|
| 73 |
entities.append(f"Entity: {entity['word']}, Label: {entity['entity_group']}, Confidence: {entity['score']:.4f}")
|
| 74 |
return "\n".join(entities)
|
| 75 |
|
|
|
|
| 76 |
def classify_image(image):
|
| 77 |
result = image_classification_pipeline(image)
|
| 78 |
classifications = []
|
|
|
|
| 80 |
classifications.append(f"Label: {item['label']}, Confidence: {item['score']:.4f}")
|
| 81 |
return "\n".join(classifications)
|
| 82 |
|
|
|
|
| 83 |
def generate_code(prompt):
|
| 84 |
result = code_generation_pipeline(prompt, max_length=100, num_return_sequences=1)
|
| 85 |
return result[0]['generated_text']
|
| 86 |
|
|
|
|
| 87 |
def fix_code(error, problem, solution, example):
|
| 88 |
prompt = f"""
|
| 89 |
**Ошибка:** {error}
|
|
|
|
| 94 |
result = code_fix_pipeline(prompt, max_length=200, num_return_sequences=1)
|
| 95 |
return result[0]['generated_text']
|
| 96 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
# Создаем интерфейс Gradio с вкладками
|
| 98 |
with gr.Blocks() as demo:
|
| 99 |
with gr.Tab("Sentiment Analysis"):
|
|
|
|
| 103 |
outputs="text",
|
| 104 |
title="Анализ тональности текста",
|
| 105 |
description="Введите текст, чтобы определить его тональность.",
|
| 106 |
+
examples=[
|
| 107 |
+
"I love programming, it's so much fun!",
|
| 108 |
+
"This movie was terrible, I hated it.",
|
| 109 |
+
"The weather is nice today."
|
| 110 |
+
],
|
| 111 |
examples_per_page=3
|
| 112 |
)
|
| 113 |
with gr.Tab("Text Summarization"):
|
|
|
|
| 117 |
outputs="text",
|
| 118 |
title="Суммаризация текста",
|
| 119 |
description="Введите текст, чтобы получить его краткое содержание.",
|
| 120 |
+
examples=[
|
| 121 |
+
"Gradio is a powerful tool for building machine learning demos. It allows developers to quickly create interactive interfaces for their models.",
|
| 122 |
+
"The weather today is sunny with a slight breeze. It's a perfect day to go outside and enjoy nature."
|
| 123 |
+
],
|
| 124 |
examples_per_page=2
|
| 125 |
)
|
| 126 |
with gr.Tab("Image Captioning"):
|
|
|
|
| 130 |
outputs="text",
|
| 131 |
title="Генерация подписи к изображению",
|
| 132 |
description="Загрузите изображение, чтобы сгенерировать его описание.",
|
| 133 |
+
examples=[
|
| 134 |
+
"https://a.d-cd.net/b977306s-1920.jpg", # Пример 1
|
| 135 |
+
"https://i.pinimg.com/originals/ba/bd/6d/babd6d37eb2dd965c7f1dfb516d54094.jpg" # Пример 2
|
| 136 |
+
],
|
| 137 |
examples_per_page=2
|
| 138 |
)
|
| 139 |
with gr.Tab("Question Answering"):
|
|
|
|
| 146 |
outputs="text",
|
| 147 |
title="Ответы на вопросы",
|
| 148 |
description="Введите контекст и вопрос, чтобы получить ответ.",
|
| 149 |
+
examples=[
|
| 150 |
+
["Gradio is a Python library for building machine learning demos. It allows developers to quickly create interactive interfaces for their models.", "What is Gradio?"],
|
| 151 |
+
["The weather today is sunny with a slight breeze. It's a perfect day to go outside and enjoy nature.", "What is the weather like today?"]
|
| 152 |
+
],
|
| 153 |
examples_per_page=2
|
| 154 |
)
|
| 155 |
with gr.Tab("Language Translation"):
|
|
|
|
| 159 |
outputs="text",
|
| 160 |
title="Перевод текста (английский → русский)",
|
| 161 |
description="Введите текст на английском, чтобы перевести его на русский.",
|
| 162 |
+
examples=[
|
| 163 |
+
"Hello, how are you?",
|
| 164 |
+
"I love machine learning and artificial intelligence."
|
| 165 |
+
],
|
| 166 |
examples_per_page=2
|
| 167 |
)
|
| 168 |
with gr.Tab("Emotion Detection"):
|
|
|
|
| 172 |
outputs="text",
|
| 173 |
title="Определение эмоций",
|
| 174 |
description="Введите текст, чтобы определить эмоцию.",
|
| 175 |
+
examples=[
|
| 176 |
+
"I am so happy today!",
|
| 177 |
+
"I feel really sad about what happened."
|
| 178 |
+
],
|
| 179 |
examples_per_page=2
|
| 180 |
)
|
| 181 |
with gr.Tab("Code Completion"):
|
|
|
|
| 185 |
outputs="text",
|
| 186 |
title="Автодополнение кода",
|
| 187 |
description="Введите начало кода, чтобы получить его продолжение.",
|
| 188 |
+
examples=[
|
| 189 |
+
"def factorial(n):",
|
| 190 |
+
"import numpy as np"
|
| 191 |
+
],
|
| 192 |
examples_per_page=2
|
| 193 |
)
|
| 194 |
with gr.Tab("Fake News Detection"):
|
|
|
|
| 198 |
outputs="text",
|
| 199 |
title="Определение фейковых новостей",
|
| 200 |
description="Введите текст новости, чтобы определить, является ли она фейковой.",
|
| 201 |
+
examples=[
|
| 202 |
+
"A new study shows that eating chocolate every day can make you live longer.",
|
| 203 |
+
"The government has secretly been working on time travel technology for decades."
|
| 204 |
+
],
|
| 205 |
examples_per_page=2
|
| 206 |
)
|
| 207 |
with gr.Tab("Named Entity Recognition (NER)"):
|
|
|
|
| 211 |
outputs="text",
|
| 212 |
title="Распознавание именованных сущностей (NER)",
|
| 213 |
description="Введите текст, чтобы извлечь из него именованные сущности.",
|
| 214 |
+
examples=[
|
| 215 |
+
"My name is John Doe and I live in New York.",
|
| 216 |
+
"Apple is looking at buying a startup in the UK for $1 billion."
|
| 217 |
+
],
|
| 218 |
examples_per_page=2
|
| 219 |
)
|
| 220 |
with gr.Tab("Image Classification"):
|
|
|
|
| 224 |
outputs="text",
|
| 225 |
title="Классификация изображений",
|
| 226 |
description="Загрузите изображение, чтобы классифицировать его.",
|
| 227 |
+
examples=[
|
| 228 |
+
"https://a.d-cd.net/b977306s-1920.jpg", # Пример 1
|
| 229 |
+
"https://i.pinimg.com/originals/ba/bd/6d/babd6d37eb2dd965c7f1dfb516d54094.jpg" # Пример 2
|
| 230 |
+
],
|
| 231 |
examples_per_page=2
|
| 232 |
)
|
| 233 |
with gr.Tab("Code Generation"):
|
|
|
|
| 237 |
outputs="text",
|
| 238 |
title="Генерация кода по запросу",
|
| 239 |
description="Введите текстовый запрос, чтобы сгенерировать код.",
|
| 240 |
+
examples=[
|
| 241 |
+
"Write a Python function to calculate the factorial of a number.",
|
| 242 |
+
"Create a JavaScript function to reverse a string."
|
| 243 |
+
],
|
| 244 |
examples_per_page=2
|
| 245 |
)
|
| 246 |
with gr.Tab("Code Fix"):
|
|
|
|
| 255 |
outputs="text",
|
| 256 |
title="Исправление кода",
|
| 257 |
description="Введите ошибку, проблему, решение и пример, чтобы получить исправленный код.",
|
| 258 |
+
examples=[
|
| 259 |
+
["SyntaxError: invalid syntax", "Missing colon at the end of the if statement", "Add a colon at the end of the if statement", "if x == 5\n print('Hello')"],
|
| 260 |
+
["NameError: name 'x' is not defined", "Variable 'x' is not defined before use", "Define the variable 'x' before using it", "print(x)\nx = 10"]
|
| 261 |
+
],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
examples_per_page=2
|
| 263 |
)
|
| 264 |
+
with gr.Tab("Image Generation (Flux)"):
|
| 265 |
gr.Interface(
|
| 266 |
+
fn=generate_image_flux,
|
| 267 |
inputs=gr.Textbox(lines=2, placeholder="Введите текстовый запрос..."),
|
| 268 |
outputs=gr.Image(type="pil", label="Сгенерированное изображение"),
|
| 269 |
+
title="Генерация изображений (Flux)",
|
| 270 |
+
description="Введите текстовый запрос, чтобы сгенерировать изображение с помощью Flux.",
|
| 271 |
examples=[
|
| 272 |
"A futuristic cityscape at night",
|
| 273 |
"A beautiful landscape with mountains and a lake",
|