DHEIVER commited on
Commit
4b310eb
·
verified ·
1 Parent(s): ce0642b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -0
app.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ import gradio as gr
3
+ from transformers import pipeline
4
+ import torch
5
+ import warnings
6
+ warnings.filterwarnings('ignore')
7
+
8
+ # Configuração de dispositivo
9
+ device = "cuda" if torch.cuda.is_available() else "cpu"
10
+
11
+ try:
12
+ # Modelos para diferentes tarefas
13
+ models = {
14
+ 'transcription': pipeline("automatic-speech-recognition", model="openai/whisper-small", device=device),
15
+ 'translation_en_pt': pipeline("translation", model="Helsinki-NLP/opus-mt-en-pt", device=device),
16
+ 'translation_pt_en': pipeline("translation", model="Helsinki-NLP/opus-mt-pt-en", device=device),
17
+ 'summarization': pipeline("summarization", model="facebook/bart-large-cnn", device=device),
18
+ 'sentiment': pipeline("sentiment-analysis", model="nlptown/bert-base-multilingual-uncased-sentiment", device=device),
19
+ 'question_answering': pipeline("question-answering", model="deepset/roberta-base-squad2", device=device),
20
+ 'chat': pipeline("text-generation", model="facebook/opt-1.3b", device=device)
21
+ }
22
+ except Exception as e:
23
+ print(f"Erro ao carregar modelos: {str(e)}")
24
+
25
+ def safe_process(func):
26
+ def wrapper(*args, **kwargs):
27
+ try:
28
+ return func(*args, **kwargs)
29
+ except Exception as e:
30
+ return f"Erro ao processar: {str(e)}"
31
+ return wrapper
32
+
33
+ @safe_process
34
+ def transcribe(audio):
35
+ if not audio:
36
+ return "Por favor, forneça um arquivo de áudio."
37
+ return models['transcription'](audio)["text"]
38
+
39
+ @safe_process
40
+ def translate(text, direction):
41
+ if not text:
42
+ return "Por favor, insira um texto para tradução."
43
+ model = models[f'translation_{direction}']
44
+ return model(text)[0]['translation_text']
45
+
46
+ @safe_process
47
+ def summarize(text):
48
+ if not text:
49
+ return "Por favor, insira um texto para resumir."
50
+ return models['summarization'](text, max_length=130, min_length=30)[0]['summary_text']
51
+
52
+ @safe_process
53
+ def analyze_sentiment(text):
54
+ if not text:
55
+ return "Por favor, insira um texto para análise."
56
+ return models['sentiment'](text)[0]['label']
57
+
58
+ @safe_process
59
+ def answer_question(question, context):
60
+ if not question or not context:
61
+ return "Por favor, forneça tanto a pergunta quanto o contexto."
62
+ return models['question_answering'](question=question, context=context)['answer']
63
+
64
+ @safe_process
65
+ def chat_response(message, history):
66
+ if not message:
67
+ return "Por favor, insira uma mensagem."
68
+ response = models['chat'](message, max_length=100, do_sample=True, temperature=0.7)
69
+ return response[0]['generated_text']
70
+
71
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
72
+ with gr.Tab("Início"):
73
+ gr.HTML(open("index.html").read())
74
+
75
+ with gr.Tab("Transcrição de Áudio"):
76
+ audio_input = gr.Audio(type="filepath", label="Upload de Áudio")
77
+ transcribe_button = gr.Button("Transcrever")
78
+ transcription_output = gr.Textbox(label="Transcrição", lines=3)
79
+ transcribe_button.click(transcribe, inputs=audio_input, outputs=transcription_output)
80
+
81
+ with gr.Tab("Tradução"):
82
+ with gr.Row():
83
+ translation_direction = gr.Radio(
84
+ ["en_pt", "pt_en"],
85
+ label="Direção da Tradução",
86
+ value="en_pt"
87
+ )
88
+ text_to_translate = gr.Textbox(label="Texto para Traduzir", lines=3)
89
+ translate_button = gr.Button("Traduzir")
90
+ translation_output = gr.Textbox(label="Tradução", lines=3)
91
+ translate_button.click(
92
+ translate,
93
+ inputs=[text_to_translate, translation_direction],
94
+ outputs=translation_output
95
+ )
96
+
97
+ with gr.Tab("Resumo"):
98
+ text_to_summarize = gr.Textbox(label="Texto para Resumir", lines=5)
99
+ summarize_button = gr.Button("Resumir")
100
+ summary_output = gr.Textbox(label="Resumo", lines=3)
101
+ summarize_button.click(summarize, inputs=text_to_summarize, outputs=summary_output)
102
+
103
+ with gr.Tab("Análise de Sentimento"):
104
+ sentiment_text = gr.Textbox(label="Texto para Análise", lines=3)
105
+ sentiment_button = gr.Button("Analisar")
106
+ sentiment_output = gr.Textbox(label="Sentimento")
107
+ sentiment_button.click(analyze_sentiment, inputs=sentiment_text, outputs=sentiment_output)
108
+
109
+ with gr.Tab("Perguntas e Respostas"):
110
+ question_input = gr.Textbox(label="Pergunta")
111
+ context_input = gr.Textbox(label="Contexto", lines=5)
112
+ qa_button = gr.Button("Responder")
113
+ qa_output = gr.Textbox(label="Resposta", lines=2)
114
+ qa_button.click(
115
+ answer_question,
116
+ inputs=[question_input, context_input],
117
+ outputs=qa_output
118
+ )
119
+
120
+ with gr.Tab("Chat"):
121
+ chatbot = gr.Chatbot()
122
+ msg = gr.Textbox(label="Mensagem")
123
+ clear = gr.Button("Limpar")
124
+
125
+ msg.submit(chat_response, [msg, chatbot], [msg, chatbot])
126
+ clear.click(lambda: None, None, chatbot, queue=False)
127
+
128
+ if __name__ == "__main__":
129
+ demo.launch(share=True)