DHEIVER commited on
Commit
317fb1f
·
verified ·
1 Parent(s): b4277da

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +171 -142
app.py CHANGED
@@ -1,171 +1,200 @@
1
  import gradio as gr
2
- from transformers import pipeline
3
- import cv2
4
- import numpy as np
5
  import torch
 
 
6
  from PIL import Image
7
- import easyocr
8
- import librosa
9
- import soundfile as sf
10
- from googletrans import Translator
11
- import spacy
12
-
13
- # 1. Reconhecimento de Texto em Imagens (OCR)
14
- def ocr_text(image):
15
- reader = easyocr.Reader(['pt', 'en'])
16
- result = reader.readtext(image)
17
- return " ".join([text[1] for text in result])
18
 
19
- # 2. Detector de Objetos
20
- def detect_objects(image):
21
- detector = pipeline('object-detection', model='facebook/detr-resnet-50')
22
- results = detector(image)
23
- annotated_image = Image.fromarray(np.array(image))
24
- for result in results:
25
- box = result['box']
26
- label = f"{result['label']}: {result['score']:.2f}"
27
- cv2.rectangle(
28
- np.array(annotated_image),
29
- (int(box['xmin']), int(box['ymin'])),
30
- (int(box['xmax']), int(box['ymax'])),
31
- (255, 0, 0),
32
- 2
33
- )
34
- return annotated_image
35
-
36
- # 3. Análise de Sentimentos
37
- def analyze_sentiment(text):
38
- classifier = pipeline("sentiment-analysis", model="neuralmind/bert-base-portuguese-cased")
39
- result = classifier(text)
40
- return f"Sentimento: {result[0]['label']}, Confiança: {result[0]['score']:.2f}"
41
 
42
- # 4. Reconhecimento de Fala
43
- def speech_to_text(audio):
44
- asr = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h")
45
- return asr(audio)["text"]
 
 
 
 
46
 
47
- # 5. Resumo de Texto
48
- def summarize_text(text):
49
- summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
50
- summary = summarizer(text, max_length=130, min_length=30)
51
- return summary[0]['summary_text']
 
 
52
 
53
- # 6. Geração de Legendas para Imagens
54
- def generate_caption(image):
55
- captioner = pipeline("image-to-text", model="nlpconnect/vit-gpt2-image-captioning")
56
- caption = captioner(image)[0]['generated_text']
57
- return caption
 
 
 
 
 
 
58
 
59
- # 7. Tradução de Texto
60
- def translate_text(text, target_lang):
61
- translator = Translator()
62
- translation = translator.translate(text, dest=target_lang)
63
- return translation.text
 
 
64
 
65
- # 8. Extração de Entidades Nomeadas (NER)
66
- def extract_entities(text):
67
- nlp = spacy.load("pt_core_news_sm")
68
- doc = nlp(text)
69
- entities = [(ent.text, ent.label_) for ent in doc.ents]
70
- return str(entities)
 
 
 
71
 
72
- # 9. Classificação de Imagens
73
- def classify_image(image):
74
- classifier = pipeline("image-classification", model="google/vit-base-patch16-224")
75
- results = classifier(image)
76
- return f"{results[0]['label']}: {results[0]['score']:.2f}"
 
 
 
 
 
 
77
 
78
- # 10. Resposta a Perguntas
79
- def answer_question(context, question):
80
- qa_pipeline = pipeline("question-answering", model="pierreguillou/bert-base-cased-squad-v1.1-portuguese")
81
- result = qa_pipeline(question=question, context=context)
82
- return result['answer']
83
 
84
  # Interface Gradio
85
- with gr.Blocks(title="Hub de Serviços IA Open Source") as demo:
86
- gr.Markdown("# 🤖 Hub de Serviços de IA Open Source")
 
87
 
88
- # 1. OCR
89
- with gr.Tab("OCR"):
90
- with gr.Row():
91
- ocr_input = gr.Image(type="numpy", label="Imagem com Texto")
92
- ocr_output = gr.Textbox(label="Texto Extraído")
93
- ocr_button = gr.Button("Extrair Texto")
94
- ocr_button.click(ocr_text, inputs=ocr_input, outputs=ocr_output)
95
 
96
- # 2. Detecção de Objetos
97
- with gr.Tab("Detector de Objetos"):
 
98
  with gr.Row():
99
- obj_input = gr.Image(type="numpy", label="Imagem")
100
- obj_output = gr.Image(label="Objetos Detectados")
101
- obj_button = gr.Button("Detectar Objetos")
102
- obj_button.click(detect_objects, inputs=obj_input, outputs=obj_output)
103
-
104
- # 3. Análise de Sentimentos
105
- with gr.Tab("Análise de Sentimentos"):
106
  with gr.Row():
107
- sent_input = gr.Textbox(label="Texto para Análise")
108
- sent_output = gr.Textbox(label="Sentimento")
109
- sent_button = gr.Button("Analisar Sentimento")
110
- sent_button.click(analyze_sentiment, inputs=sent_input, outputs=sent_output)
 
 
 
 
 
 
 
 
 
111
 
112
- # 4. Reconhecimento de Fala
113
- with gr.Tab("Reconhecimento de Fala"):
 
114
  with gr.Row():
115
- speech_input = gr.Audio(type="numpy", label="Áudio")
116
- speech_output = gr.Textbox(label="Texto Transcrito")
117
- speech_button = gr.Button("Transcrever Áudio")
118
- speech_button.click(speech_to_text, inputs=speech_input, outputs=speech_output)
119
-
120
- # 5. Resumo de Texto
121
- with gr.Tab("Resumo de Texto"):
122
  with gr.Row():
123
- sum_input = gr.Textbox(label="Texto para Resumir")
124
- sum_output = gr.Textbox(label="Resumo")
125
- sum_button = gr.Button("Gerar Resumo")
126
- sum_button.click(summarize_text, inputs=sum_input, outputs=sum_output)
 
 
 
 
 
 
 
 
 
127
 
128
- # 6. Geração de Legendas
129
- with gr.Tab("Legendas para Imagens"):
 
130
  with gr.Row():
131
- cap_input = gr.Image(type="numpy", label="Imagem")
132
- cap_output = gr.Textbox(label="Legenda")
133
- cap_button = gr.Button("Gerar Legenda")
134
- cap_button.click(generate_caption, inputs=cap_input, outputs=cap_output)
135
-
136
- # 7. Tradução
137
- with gr.Tab("Tradução"):
 
 
138
  with gr.Row():
139
- trans_input = gr.Textbox(label="Texto para Traduzir")
140
- trans_lang = gr.Dropdown(choices=["en", "es", "fr", "de", "it"], label="Idioma Alvo")
141
- trans_output = gr.Textbox(label="Tradução")
 
 
 
 
 
 
 
142
  trans_button = gr.Button("Traduzir")
143
- trans_button.click(translate_text, inputs=[trans_input, trans_lang], outputs=trans_output)
144
-
145
- # 8. NER
146
- with gr.Tab("Extração de Entidades"):
147
- with gr.Row():
148
- ner_input = gr.Textbox(label="Texto para Análise")
149
- ner_output = gr.Textbox(label="Entidades Encontradas")
150
- ner_button = gr.Button("Extrair Entidades")
151
- ner_button.click(extract_entities, inputs=ner_input, outputs=ner_output)
152
-
153
- # 9. Classificação de Imagens
154
- with gr.Tab("Classificação de Imagens"):
155
- with gr.Row():
156
- class_input = gr.Image(type="numpy", label="Imagem")
157
- class_output = gr.Textbox(label="Classificação")
158
- class_button = gr.Button("Classificar Imagem")
159
- class_button.click(classify_image, inputs=class_input, outputs=class_output)
160
 
161
- # 10. Resposta a Perguntas
162
- with gr.Tab("Resposta a Perguntas"):
 
163
  with gr.Row():
164
- qa_context = gr.Textbox(label="Contexto")
165
- qa_question = gr.Textbox(label="Pergunta")
166
- qa_output = gr.Textbox(label="Resposta")
167
- qa_button = gr.Button("Responder")
168
- qa_button.click(answer_question, inputs=[qa_context, qa_question], outputs=qa_output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
 
170
  if __name__ == "__main__":
171
  demo.launch()
 
1
  import gradio as gr
2
+ from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
3
+ from transformers import MarianMTModel, MarianTokenizer
4
+ from diffusers import StableDiffusionPipeline, DiffusionPipeline
5
  import torch
6
+ import numpy as np
7
+ import imageio
8
  from PIL import Image
9
+ from modelscope.pipelines import pipeline as ms_pipeline
10
+ from modelscope.outputs import OutputKeys
 
 
 
 
 
 
 
 
 
11
 
12
+ class MultiModalServices:
13
+ def __init__(self):
14
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
15
+ self.image_generator = None
16
+ self.video_generator = None
17
+ self.translator = None
18
+ self.sentiment_analyzer = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
+ def load_image_generator(self):
21
+ if self.image_generator is None:
22
+ model_id = "CompVis/stable-diffusion-v1-4"
23
+ self.image_generator = StableDiffusionPipeline.from_pretrained(
24
+ model_id,
25
+ torch_dtype=torch.float32
26
+ ).to(self.device)
27
+ return self.image_generator
28
 
29
+ def load_video_generator(self):
30
+ if self.video_generator is None:
31
+ self.video_generator = ms_pipeline(
32
+ 'text-to-video-synthesis',
33
+ 'damo/text-to-video-synthesis'
34
+ )
35
+ return self.video_generator
36
 
37
+ def generate_image(self, prompt, num_images=1):
38
+ try:
39
+ generator = self.load_image_generator()
40
+ images = generator(
41
+ prompt,
42
+ num_images_per_prompt=num_images,
43
+ guidance_scale=7.5
44
+ ).images
45
+ return images[0] if num_images == 1 else images
46
+ except Exception as e:
47
+ return f"Erro na geração de imagem: {str(e)}"
48
 
49
+ def generate_video(self, prompt, duration=3):
50
+ try:
51
+ generator = self.load_video_generator()
52
+ output = generator({'text': prompt})
53
+ return output[OutputKeys.OUTPUT_VIDEO]
54
+ except Exception as e:
55
+ return f"Erro na geração de vídeo: {str(e)}"
56
 
57
+ def translate(self, text, src_lang, tgt_lang):
58
+ if self.translator is None:
59
+ model_name = f'Helsinki-NLP/opus-mt-{src_lang}-{tgt_lang}'
60
+ self.translator = pipeline('translation', model=model_name)
61
+ try:
62
+ result = self.translator(text)[0]['translation_text']
63
+ return result
64
+ except Exception as e:
65
+ return f"Erro na tradução: {str(e)}"
66
 
67
+ def analyze_sentiment(self, text):
68
+ if self.sentiment_analyzer is None:
69
+ self.sentiment_analyzer = pipeline(
70
+ 'sentiment-analysis',
71
+ model='nlptown/bert-base-multilingual-uncased-sentiment'
72
+ )
73
+ try:
74
+ result = self.sentiment_analyzer(text)[0]
75
+ return f"Sentimento: {result['label']}, Confiança: {result['score']:.2f}"
76
+ except Exception as e:
77
+ return f"Erro na análise: {str(e)}"
78
 
79
+ # Instância global dos serviços
80
+ services = MultiModalServices()
 
 
 
81
 
82
  # Interface Gradio
83
+ with gr.Blocks(title="Serviços de IA Multimodal") as demo:
84
+ gr.Markdown("""
85
+ # 🎨 Hub de Serviços de IA Multimodal
86
 
87
+ Esta aplicação oferece serviços de geração de imagem, vídeo e processamento de texto.
88
+ """)
 
 
 
 
 
89
 
90
+ # 1. Geração de Imagem
91
+ with gr.Tab("Geração de Imagem"):
92
+ gr.Markdown("### Gerador de Imagens com Stable Diffusion")
93
  with gr.Row():
94
+ img_prompt = gr.Textbox(
95
+ label="Descrição da imagem",
96
+ placeholder="Descreva a imagem que deseja gerar...",
97
+ lines=3
98
+ )
99
+ img_output = gr.Image(label="Imagem Gerada")
 
100
  with gr.Row():
101
+ img_num = gr.Slider(
102
+ minimum=1,
103
+ maximum=4,
104
+ value=1,
105
+ step=1,
106
+ label="Número de imagens"
107
+ )
108
+ img_button = gr.Button("Gerar Imagem")
109
+ img_button.click(
110
+ services.generate_image,
111
+ inputs=[img_prompt, img_num],
112
+ outputs=img_output
113
+ )
114
 
115
+ # 2. Geração de Vídeo
116
+ with gr.Tab("Geração de Vídeo"):
117
+ gr.Markdown("### Gerador de Vídeos")
118
  with gr.Row():
119
+ vid_prompt = gr.Textbox(
120
+ label="Descrição do vídeo",
121
+ placeholder="Descreva o vídeo que deseja gerar...",
122
+ lines=3
123
+ )
124
+ vid_output = gr.Video(label="Vídeo Gerado")
 
125
  with gr.Row():
126
+ vid_duration = gr.Slider(
127
+ minimum=1,
128
+ maximum=10,
129
+ value=3,
130
+ step=1,
131
+ label="Duração (segundos)"
132
+ )
133
+ vid_button = gr.Button("Gerar Vídeo")
134
+ vid_button.click(
135
+ services.generate_video,
136
+ inputs=[vid_prompt, vid_duration],
137
+ outputs=vid_output
138
+ )
139
 
140
+ # 3. Tradução
141
+ with gr.Tab("Tradutor"):
142
+ gr.Markdown("### Tradutor Multilíngue")
143
  with gr.Row():
144
+ trans_input = gr.Textbox(
145
+ label="Texto para traduzir",
146
+ placeholder="Digite o texto aqui...",
147
+ lines=3
148
+ )
149
+ trans_output = gr.Textbox(
150
+ label="Tradução",
151
+ lines=3
152
+ )
153
  with gr.Row():
154
+ src_lang = gr.Dropdown(
155
+ choices=["en", "pt", "es", "fr", "de"],
156
+ value="en",
157
+ label="Idioma de origem"
158
+ )
159
+ tgt_lang = gr.Dropdown(
160
+ choices=["pt", "en", "es", "fr", "de"],
161
+ value="pt",
162
+ label="Idioma de destino"
163
+ )
164
  trans_button = gr.Button("Traduzir")
165
+ trans_button.click(
166
+ services.translate,
167
+ inputs=[trans_input, src_lang, tgt_lang],
168
+ outputs=trans_output
169
+ )
 
 
 
 
 
 
 
 
 
 
 
 
170
 
171
+ # 4. Análise de Sentimentos
172
+ with gr.Tab("Análise de Sentimentos"):
173
+ gr.Markdown("### Análise de Sentimentos Multilíngue")
174
  with gr.Row():
175
+ sent_input = gr.Textbox(
176
+ label="Texto para análise",
177
+ placeholder="Digite o texto para analisar o sentimento...",
178
+ lines=3
179
+ )
180
+ sent_output = gr.Textbox(
181
+ label="Resultado da análise",
182
+ lines=2
183
+ )
184
+ sent_button = gr.Button("Analisar Sentimento")
185
+ sent_button.click(
186
+ services.analyze_sentiment,
187
+ inputs=sent_input,
188
+ outputs=sent_output
189
+ )
190
+
191
+ gr.Markdown("""
192
+ ### Notas:
193
+ - A geração de imagens e vídeos requer GPU para melhor performance
194
+ - Os modelos são carregados sob demanda para economizar memória
195
+ - Primeira execução pode ser mais lenta devido ao download dos modelos
196
+ - Todos os modelos são open source
197
+ """)
198
 
199
  if __name__ == "__main__":
200
  demo.launch()