Spaces:
Runtime error
Runtime error
import gradio as gr | |
from transformers import pipeline | |
# Загружаем модели для анализа тональности, суммаризации текста, генерации подписей к изображениям, ответов на вопросы, перевода текста, определения эмоций и автодополнения кода | |
sentiment_pipeline = pipeline("sentiment-analysis") | |
summarization_pipeline = pipeline("summarization") | |
image_captioning_pipeline = pipeline("image-to-text") | |
qa_pipeline = pipeline("question-answering") | |
translation_pipeline = pipeline("translation_en_to_ru", model="Helsinki-NLP/opus-mt-en-ru") | |
emotion_pipeline = pipeline("text-classification", model="bhadresh-savani/distilbert-base-uncased-emotion") | |
code_completion_pipeline = pipeline("text-generation", model="Salesforce/codegen-350M-mono") | |
# Функция для анализа тональности текста | |
def analyze_sentiment(text): | |
result = sentiment_pipeline(text)[0] | |
return f"Label: {result['label']}, Confidence: {result['score']:.4f}" | |
# Функция для суммаризации текста | |
def summarize_text(text): | |
result = summarization_pipeline(text, max_length=50, min_length=25, do_sample=False) | |
return result[0]['summary_text'] | |
# Функция для генерации подписи к изображению | |
def generate_caption(image): | |
result = image_captioning_pipeline(image) | |
return result[0]['generated_text'] | |
# Функция для ответов на вопросы | |
def answer_question(context, question): | |
result = qa_pipeline(question=question, context=context) | |
return f"Answer: {result['answer']}, Confidence: {result['score']:.4f}" | |
# Функция для перевода текста | |
def translate_text(text): | |
result = translation_pipeline(text) | |
return result[0]['translation_text'] | |
# Функция для определения эмоций | |
def detect_emotion(text): | |
result = emotion_pipeline(text)[0] | |
return f"Emotion: {result['label']}, Confidence: {result['score']:.4f}" | |
# Функция для автодополнения кода | |
def complete_code(code): | |
result = code_completion_pipeline(code, max_length=50, num_return_sequences=1) | |
return result[0]['generated_text'] | |
# Примеры текстов для анализа тональности | |
sentiment_examples = [ | |
"I love programming, it's so much fun!", | |
"This movie was terrible, I hated it.", | |
"The weather is nice today.", | |
"I feel so frustrated with this project.", | |
"Gradio is an amazing tool for building ML demos!" | |
] | |
# Примеры текстов для суммаризации | |
summarization_examples = [ | |
"Gradio is a powerful tool for building machine learning demos. It allows developers to quickly create interactive interfaces for their models.", | |
"The weather today is sunny with a slight breeze. It's a perfect day to go outside and enjoy nature.", | |
"Artificial intelligence is transforming industries by automating tasks and providing insights from large datasets." | |
] | |
# Примеры изображений для генерации подписей | |
image_examples = [ | |
"https://a.d-cd.net/b977306s-1920.jpg", # Пример 1 | |
"https://i.pinimg.com/originals/ba/bd/6d/babd6d37eb2dd965c7f1dfb516d54094.jpg", # Пример 2 | |
"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 | |
] | |
# Примеры для ответов на вопросы | |
qa_examples = [ | |
["Gradio is a Python library for building machine learning demos. It allows developers to quickly create interactive interfaces for their models.", "What is Gradio?"], | |
["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?"], | |
["Artificial intelligence is transforming industries by automating tasks and providing insights from large datasets.", "How is AI transforming industries?"] | |
] | |
# Примеры текстов для перевода | |
translation_examples = [ | |
"Hello, how are you?", | |
"I love machine learning and artificial intelligence.", | |
"The weather is beautiful today." | |
] | |
# Примеры текстов для определения эмоций | |
emotion_examples = [ | |
"I am so happy today!", | |
"I feel really sad about what happened.", | |
"This situation makes me angry.", | |
"I am scared of the dark.", | |
"I am surprised by the results." | |
] | |
# Примеры кода для автодополнения | |
code_examples = [ | |
"def factorial(n):", | |
"import numpy as np", | |
"for i in range(10):" | |
] | |
# Создаем интерфейс Gradio с вкладками | |
with gr.Blocks() as demo: | |
with gr.Tab("Sentiment Analysis"): | |
gr.Interface( | |
fn=analyze_sentiment, | |
inputs=gr.Textbox(lines=2, placeholder="Введите текст для анализа тональности..."), | |
outputs="text", | |
title="Анализ тональности текста", | |
description="Введите текст, чтобы определить его тональность.", | |
examples=sentiment_examples, | |
examples_per_page=3 | |
) | |
with gr.Tab("Text Summarization"): | |
gr.Interface( | |
fn=summarize_text, | |
inputs=gr.Textbox(lines=5, placeholder="Введите текст для суммаризации..."), | |
outputs="text", | |
title="Суммаризация текста", | |
description="Введите текст, чтобы получить его краткое содержание.", | |
examples=summarization_examples, | |
examples_per_page=2 | |
) | |
with gr.Tab("Image Captioning"): | |
gr.Interface( | |
fn=generate_caption, | |
inputs=gr.Image(type="pil", label="Загрузите изображение"), | |
outputs="text", | |
title="Генерация подписи к изображению", | |
description="Загрузите изображение, чтобы сгенерировать его описание.", | |
examples=image_examples, | |
examples_per_page=2 | |
) | |
with gr.Tab("Question Answering"): | |
gr.Interface( | |
fn=answer_question, | |
inputs=[ | |
gr.Textbox(lines=5, placeholder="Введите контекст..."), | |
gr.Textbox(lines=2, placeholder="Введите вопрос...") | |
], | |
outputs="text", | |
title="Ответы на вопросы", | |
description="Введите контекст и вопрос, чтобы получить ответ.", | |
examples=qa_examples, | |
examples_per_page=2 | |
) | |
with gr.Tab("Language Translation"): | |
gr.Interface( | |
fn=translate_text, | |
inputs=gr.Textbox(lines=2, placeholder="Введите текст на английском..."), | |
outputs="text", | |
title="Перевод текста (английский → русский)", | |
description="Введите текст на английском, чтобы перевести его на русский.", | |
examples=translation_examples, | |
examples_per_page=2 | |
) | |
with gr.Tab("Emotion Detection"): | |
gr.Interface( | |
fn=detect_emotion, | |
inputs=gr.Textbox(lines=2, placeholder="Введите текст для определения эмоции..."), | |
outputs="text", | |
title="Определение эмоций", | |
description="Введите текст, чтобы определить эмоцию.", | |
examples=emotion_examples, | |
examples_per_page=2 | |
) | |
with gr.Tab("Code Completion"): | |
gr.Interface( | |
fn=complete_code, | |
inputs=gr.Textbox(lines=5, placeholder="Введите начало кода..."), | |
outputs="text", | |
title="Автодополнение кода", | |
description="Введите начало кода, чтобы получить его продолжение.", | |
examples=code_examples, | |
examples_per_page=2 | |
) | |
# Запускаем интерфейс | |
demo.launch() |