JJhooww commited on
Commit
154341a
·
verified ·
1 Parent(s): 2696ab9

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +526 -191
README.md CHANGED
@@ -1,199 +1,534 @@
1
  ---
2
  library_name: transformers
3
- tags: []
 
 
 
 
 
 
 
 
 
4
  ---
 
5
 
6
- # Model Card for Model ID
7
-
8
- <!-- Provide a quick summary of what the model is/does. -->
9
-
10
-
11
-
12
- ## Model Details
13
-
14
- ### Model Description
15
-
16
- <!-- Provide a longer summary of what this model is. -->
17
-
18
- This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
-
20
- - **Developed by:** [More Information Needed]
21
- - **Funded by [optional]:** [More Information Needed]
22
- - **Shared by [optional]:** [More Information Needed]
23
- - **Model type:** [More Information Needed]
24
- - **Language(s) (NLP):** [More Information Needed]
25
- - **License:** [More Information Needed]
26
- - **Finetuned from model [optional]:** [More Information Needed]
27
-
28
- ### Model Sources [optional]
29
-
30
- <!-- Provide the basic links for the model. -->
31
-
32
- - **Repository:** [More Information Needed]
33
- - **Paper [optional]:** [More Information Needed]
34
- - **Demo [optional]:** [More Information Needed]
35
-
36
- ## Uses
37
-
38
- <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
-
40
- ### Direct Use
41
-
42
- <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
-
44
- [More Information Needed]
45
-
46
- ### Downstream Use [optional]
47
-
48
- <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
-
50
- [More Information Needed]
51
-
52
- ### Out-of-Scope Use
53
-
54
- <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
-
56
- [More Information Needed]
57
-
58
- ## Bias, Risks, and Limitations
59
-
60
- <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
-
62
- [More Information Needed]
63
-
64
- ### Recommendations
65
-
66
- <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
-
68
- Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
-
70
- ## How to Get Started with the Model
71
-
72
- Use the code below to get started with the model.
73
-
74
- [More Information Needed]
75
-
76
- ## Training Details
77
-
78
- ### Training Data
79
-
80
- <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
-
82
- [More Information Needed]
83
-
84
- ### Training Procedure
85
-
86
- <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
-
88
- #### Preprocessing [optional]
89
-
90
- [More Information Needed]
91
-
92
-
93
- #### Training Hyperparameters
94
-
95
- - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
-
97
- #### Speeds, Sizes, Times [optional]
98
-
99
- <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
-
101
- [More Information Needed]
102
-
103
- ## Evaluation
104
-
105
- <!-- This section describes the evaluation protocols and provides the results. -->
106
-
107
- ### Testing Data, Factors & Metrics
108
-
109
- #### Testing Data
110
-
111
- <!-- This should link to a Dataset Card if possible. -->
112
-
113
- [More Information Needed]
114
-
115
- #### Factors
116
-
117
- <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
-
119
- [More Information Needed]
120
-
121
- #### Metrics
122
-
123
- <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
-
125
- [More Information Needed]
126
-
127
- ### Results
128
-
129
- [More Information Needed]
130
-
131
- #### Summary
132
-
133
-
134
-
135
- ## Model Examination [optional]
136
-
137
- <!-- Relevant interpretability work for the model goes here -->
138
-
139
- [More Information Needed]
140
-
141
- ## Environmental Impact
142
-
143
- <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
-
145
- Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
-
147
- - **Hardware Type:** [More Information Needed]
148
- - **Hours used:** [More Information Needed]
149
- - **Cloud Provider:** [More Information Needed]
150
- - **Compute Region:** [More Information Needed]
151
- - **Carbon Emitted:** [More Information Needed]
152
-
153
- ## Technical Specifications [optional]
154
-
155
- ### Model Architecture and Objective
156
-
157
- [More Information Needed]
158
-
159
- ### Compute Infrastructure
160
-
161
- [More Information Needed]
162
-
163
- #### Hardware
164
-
165
- [More Information Needed]
166
-
167
- #### Software
168
-
169
- [More Information Needed]
170
-
171
- ## Citation [optional]
172
-
173
- <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
-
175
- **BibTeX:**
176
-
177
- [More Information Needed]
178
-
179
- **APA:**
180
-
181
- [More Information Needed]
182
-
183
- ## Glossary [optional]
184
-
185
- <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
-
187
- [More Information Needed]
188
-
189
- ## More Information [optional]
190
-
191
- [More Information Needed]
192
 
193
- ## Model Card Authors [optional]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
 
195
- [More Information Needed]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
 
197
- ## Model Card Contact
198
 
199
- [More Information Needed]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  library_name: transformers
3
+ license: apache-2.0
4
+ datasets:
5
+ - JJhooww/system_chat_portuguese
6
+ - JJhooww/rag_agente
7
+ - JJhooww/chamada_de_funcao
8
+ - JJhooww/open_perfect_ptbr_sharegpt_multiturn
9
+ language:
10
+ - pt
11
+ base_model:
12
+ - Qwen/Qwen2-VL-7B-Instruct
13
  ---
14
+ Aqui está a apresentação traduzida para o português:
15
 
16
+ ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
+ ### **Fluxi AI - Small Vision 🤖✨**
19
+
20
+ 🧠 **Inteligência Multimodal**
21
+ 🗣️ **Compreensão de Múltiplos Idiomas**
22
+ 🛠️ **Capacidade de Executar Funções**
23
+ 📚 **RAG Avançado**
24
+ 🤝 **Interação Natural e Amigável**
25
+
26
+ ## **Modelo Base**
27
+ Este assistente é baseado no modelo [Qwen2-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct), um poderoso modelo de linguagem multimodal desenvolvido pela Qwen. As principais características incluem:
28
+
29
+ - **7 bilhões de parâmetros**
30
+ - **Arquitetura avançada para visão e linguagem**
31
+ - **Suporte a múltiplas resoluções de imagem**
32
+ - **Capacidade de processamento de vídeo**
33
+ - **Otimizações específicas para tarefas multimodais**
34
+
35
+ ## **Visão Geral do Modelo**
36
+ Um assistente de IA versátil, capaz de lidar com interações multimodais, incluindo **texto, imagens e vídeos**. O modelo suporta **chamadas de função**, **RAG (Geração Aumentada por Recuperação)** e **interações guiadas pelo sistema**, com capacidades aprimoradas em português.
37
+
38
+ ## **Principais Funcionalidades**
39
+
40
+ ### **Processamento Multimodal**
41
+ ✅ **Geração e compreensão de texto**
42
+ ✅ **Análise e entendimento de imagens**
43
+ ✅ **Compreensão de vídeos (até 20+ minutos)**
44
+ ✅ **Suporte a diversos formatos de entrada:**
45
+ - Arquivos locais
46
+ - Imagens em Base64
47
+ - URLs
48
+ - Combinação de imagens e vídeos intercalados
49
+
50
+ ### **Suporte a Múltiplos Idiomas**
51
+ 🌎 O modelo compreende e processa vários idiomas, incluindo:
52
+ - **Português (suporte aprimorado)**
53
+ - **Inglês**
54
+ - **Espanhol, Francês, Alemão e outras línguas europeias**
55
+ - **Japonês e Coreano**
56
+ - **Árabe e Vietnamita**
57
+
58
+ ### **Principais Recursos**
59
+
60
+ #### **1. Chamadas de Função**
61
+ ⚙️ **Capacidade de executar funções pré-definidas**
62
+ 📄 **Manipulação estruturada de entrada/saída**
63
+ 🛠️ **Suporte para parâmetros complexos**
64
+ 🇧🇷 **Otimização para chamadas de função em português**
65
+
66
+ #### **2. Geração Aumentada por Recuperação (RAG)**
67
+ 📚 **Integração de contexto com documentos**
68
+ 🔎 **Extração de informações relevantes**
69
+ 🤖 **Respostas contextuais e adaptadas**
70
+ 🇧🇷 **Otimização para conteúdos em português**
71
+
72
+ #### **3. Interações Guiadas pelo Sistema**
73
+ 👥 **Respostas baseadas em funções e papéis**
74
+ 📌 **Adaptação a diferentes áreas de conhecimento**
75
+ 📖 **Compreensão contextual aprimorada**
76
+ 🇧🇷 **Otimização específica para agentes em português**
77
+
78
+ ## **Exemplos de Implementação**
79
+
80
+ ### **1. Exemplo de Chamada de Função**
81
+ ```python
82
+ # Estrutura de um dataset de chamada de função
83
+ messages = [
84
+ {
85
+ "role": "system",
86
+ "content": [{
87
+ "type": "text",
88
+ "text": """# Ferramentas
89
+
90
+ Você pode chamar uma ou mais funções para auxiliar na consulta do usuário.
91
+
92
+ Você recebe assinaturas de função nas tags XML <tools></tools>:
93
+ <tools>
94
+ {
95
+ "type": "function",
96
+ "function": {
97
+ "name": "criar_contato",
98
+ "description": "Criar um novo contato",
99
+ "parameters": {
100
+ "type": "object",
101
+ "properties": {
102
+ "nome": {"type": "string", "description": "O nome do contato"},
103
+ "email": {"type": "string", "description": "O endereço de e-mail do contato"}
104
+ },
105
+ "required": ["nome", "email"]
106
+ }
107
+ }
108
+ }
109
+ </tools>"""
110
+ }]
111
+ },
112
+ {
113
+ "role": "user",
114
+ "content": [{
115
+ "type": "text",
116
+ "text": "Eu preciso criar um novo contato para meu amigo John Doe. O email dele é [email protected]."
117
+ }]
118
+ }
119
+ ]
120
+
121
+ # Resposta do assistente
122
+ response = {
123
+ "role": "assistant",
124
+ "content": [{
125
+ "type": "text",
126
+ "text": "<tool_call>\n{'name': 'criar_contato', 'arguments': {'nome': 'John Doe', 'email': '[email protected]'}}</tool_call>"
127
+ }]
128
+ }
129
+ ```
130
+
131
+ ### **2. Exemplo de Implementação RAG**
132
+ ```python
133
+ # Estrutura de um dataset RAG
134
+ messages = [
135
+ {
136
+ "role": "user",
137
+ "content": [{
138
+ "type": "text",
139
+ "text": "Quais são os principais países de origem dos turistas estrangeiros que visitam o Brasil?"
140
+ }]
141
+ },
142
+ {
143
+ "role": "system",
144
+ "content": [{
145
+ "type": "text",
146
+ "text": "{'doc04': {'text': 'O Brasil recebeu mais de 6 milhões de turistas estrangeiros, principalmente da Argentina, Estados Unidos, Paraguai, Chile, Uruguai e França...'}}"
147
+ }]
148
+ }
149
+ ]
150
+
151
+ # Resposta do assistente
152
+ response = {
153
+ "role": "assistant",
154
+ "content": [{
155
+ "type": "text",
156
+ "text": "Os principais países de origem dos turistas estrangeiros que visitam o Brasil são:\n\n- Argentina\n- Estados Unidos\n- Paraguai\n- Chile\n- Uruguai\n- França"
157
+ }]
158
+ }
159
+ ```
160
+
161
+ ### **3. Exemplo de Agente Guiado pelo Sistema**
162
+ ```python
163
+ # Configuração de um agente guiado pelo sistema
164
+ messages = [
165
+ {
166
+ "role": "system",
167
+ "content": [{
168
+ "type": "text",
169
+ "text": "Você é um especialista em várias disciplinas científicas, incluindo física, química e biologia. Explique conceitos, teorias e fenômenos científicos de uma maneira envolvente e acessível."
170
+ }]
171
+ },
172
+ {
173
+ "role": "user",
174
+ "content": [{
175
+ "type": "text",
176
+ "text": "Pode me ajudar a escrever um ensaio sobre desmatamento?"
177
+ }]
178
+ }
179
+ ]
180
+ ```
181
+
182
+ ## **Otimizações para o Idioma Português**
183
+
184
+ ### **Chamadas de Função**
185
+ ✔️ **Nomes e descrições de funções em português**
186
+ ✔️ **Convenções brasileiras para nomeação de parâmetros**
187
+ ✔️ **Mensagens de erro e respostas localizadas**
188
+ ✔️ **Seleção de funções baseada em casos de uso do Brasil**
189
+
190
+ ### **RAG Aprimorado**
191
+ 📜 **Recuperação de conteúdo otimizada para português**
192
+ 🌎 **Prioridade para contexto brasileiro**
193
+ 🔍 **Maior precisão na extração de informações locais**
194
+ 📝 **Melhoria no reconhecimento de padrões do idioma**
195
+
196
+ ### **Aprimoramentos Específicos para Agentes**
197
+ 🎭 **Contexto cultural brasileiro aprimorado**
198
+ 📌 **Integração com conhecimento regional**
199
+ 🗣️ **Melhoria na compreensão das nuances do português**
200
+ 📚 **Otimização para domínios específicos do Brasil**
201
 
202
+ ---
203
+ ## Requisitos
204
+
205
+ O código do Qwen2-VL está disponível na versão mais recente do Hugging Face Transformers, e recomendamos que você construa a partir do código-fonte com o comando:
206
+
207
+ ```bash
208
+ pip install git+https://github.com/huggingface/transformers
209
+ ```
210
+
211
+ Caso contrário, você pode encontrar o seguinte erro:
212
+
213
+ ```
214
+ KeyError: 'qwen2_vl'
215
+ ```
216
+
217
+ ## Início Rápido
218
+
219
+ Oferecemos um conjunto de ferramentas para ajudá-lo a lidar com vários tipos de entrada visual de forma mais conveniente. Isso inclui base64, URLs e imagens e vídeos intercalados. Você pode instalá-lo com o comando:
220
+
221
+ ```bash
222
+ pip install qwen-vl-utils
223
+ ```
224
+
225
+ Aqui mostramos um trecho de código para mostrar como usar o modelo de chat com `transformers` e `qwen_vl_utils`:
226
+
227
+ ```python
228
+ from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
229
+ from qwen_vl_utils import process_vision_info
230
+
231
+ # Carregar o modelo no(s) dispositivo(s) disponível(is)
232
+ model = Qwen2VLForConditionalGeneration.from_pretrained(
233
+ "Qwen/Qwen2-VL-7B-Instruct", torch_dtype="auto", device_map="auto"
234
+ )
235
+
236
+ # Recomendamos habilitar o flash_attention_2 para melhor aceleração e economia de memória, especialmente em cenários com múltiplas imagens e vídeos.
237
+ # model = Qwen2VLForConditionalGeneration.from_pretrained(
238
+ # "Qwen/Qwen2-VL-7B-Instruct",
239
+ # torch_dtype=torch.bfloat16,
240
+ # attn_implementation="flash_attention_2",
241
+ # device_map="auto",
242
+ # )
243
+
244
+ # Processador padrão
245
+ processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
246
+
247
+ # O intervalo padrão para o número de tokens visuais por imagem no modelo é de 4-16384. Você pode configurar min_pixels e max_pixels conforme suas necessidades, como um intervalo de contagem de tokens de 256-1280, para equilibrar velocidade e uso de memória.
248
+ # min_pixels = 256*28*28
249
+ # max_pixels = 1280*28*28
250
+ # processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels)
251
+
252
+ messages = [
253
+ {
254
+ "role": "user",
255
+ "content": [
256
+ {
257
+ "type": "image",
258
+ "image": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
259
+ },
260
+ {"type": "text", "text": "Descreva esta imagem."},
261
+ ],
262
+ }
263
+ ]
264
+
265
+ # Preparação para inferência
266
+ text = processor.apply_chat_template(
267
+ messages, tokenize=False, add_generation_prompt=True
268
+ )
269
+ image_inputs, video_inputs = process_vision_info(messages)
270
+ inputs = processor(
271
+ text=[text],
272
+ images=image_inputs,
273
+ videos=video_inputs,
274
+ padding=True,
275
+ return_tensors="pt",
276
+ )
277
+ inputs = inputs.to("cuda")
278
+
279
+ # Inferência: Geração da saída
280
+ generated_ids = model.generate(**inputs, max_new_tokens=128)
281
+ generated_ids_trimmed = [
282
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
283
+ ]
284
+ output_text = processor.batch_decode(
285
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
286
+ )
287
+ print(output_text)
288
+ ```
289
+
290
+ <details>
291
+ <summary>Sem o qwen_vl_utils</summary>
292
+
293
+ ```python
294
+ from PIL import Image
295
+ import requests
296
+ import torch
297
+ from torchvision import io
298
+ from typing import Dict
299
+ from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
300
+
301
+ # Carregar o modelo em precisão reduzida no(s) dispositivo(s) disponível(is)
302
+ model = Qwen2VLForConditionalGeneration.from_pretrained(
303
+ "Qwen/Qwen2-VL-7B-Instruct", torch_dtype="auto", device_map="auto"
304
+ )
305
+ processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
306
+
307
+ # Imagem
308
+ url = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg"
309
+ image = Image.open(requests.get(url, stream=True).raw)
310
+
311
+ conversation = [
312
+ {
313
+ "role": "user",
314
+ "content": [
315
+ {
316
+ "type": "image",
317
+ },
318
+ {"type": "text", "text": "Descreva esta imagem."},
319
+ ],
320
+ }
321
+ ]
322
+
323
+ # Pré-processamento das entradas
324
+ text_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
325
+ # Saída esperada: '<|im_start|>system\nVocê é um assistente útil.<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>Descreva esta imagem.<|im_end|>\n<|im_start|>assistant\n'
326
+
327
+ inputs = processor(
328
+ text=[text_prompt], images=[image], padding=True, return_tensors="pt"
329
+ )
330
+ inputs = inputs.to("cuda")
331
+
332
+ # Inferência: Geração da saída
333
+ output_ids = model.generate(**inputs, max_new_tokens=128)
334
+ generated_ids = [
335
+ output_ids[len(input_ids) :]
336
+ for input_ids, output_ids in zip(inputs.input_ids, output_ids)
337
+ ]
338
+ output_text = processor.batch_decode(
339
+ generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
340
+ )
341
+ print(output_text)
342
+ ```
343
+
344
+ </details>
345
+
346
+ <details>
347
+ <summary>Inferência com múltiplas imagens</summary>
348
+
349
+ ```python
350
+ # Mensagens contendo várias imagens e uma consulta em texto
351
+ messages = [
352
+ {
353
+ "role": "user",
354
+ "content": [
355
+ {"type": "image", "image": "file:///path/to/image1.jpg"},
356
+ {"type": "image", "image": "file:///path/to/image2.jpg"},
357
+ {"type": "text", "text": "Identifique as semelhanças entre essas imagens."},
358
+ ],
359
+ }
360
+ ]
361
+
362
+ # Preparação para inferência
363
+ text = processor.apply_chat_template(
364
+ messages, tokenize=False, add_generation_prompt=True
365
+ )
366
+ image_inputs, video_inputs = process_vision_info(messages)
367
+ inputs = processor(
368
+ text=[text],
369
+ images=image_inputs,
370
+ videos=video_inputs,
371
+ padding=True,
372
+ return_tensors="pt",
373
+ )
374
+ inputs = inputs.to("cuda")
375
+
376
+ # Inferência
377
+ generated_ids = model.generate(**inputs, max_new_tokens=128)
378
+ generated_ids_trimmed = [
379
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
380
+ ]
381
+ output_text = processor.batch_decode(
382
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
383
+ )
384
+ print(output_text)
385
+ ```
386
+
387
+ </details>
388
+
389
+ <details>
390
+ <summary>Inferência com vídeo</summary>
391
+
392
+ ```python
393
+ # Mensagens contendo uma lista de imagens como vídeo e uma consulta em texto
394
+ messages = [
395
+ {
396
+ "role": "user",
397
+ "content": [
398
+ {
399
+ "type": "video",
400
+ "video": [
401
+ "file:///path/to/frame1.jpg",
402
+ "file:///path/to/frame2.jpg",
403
+ "file:///path/to/frame3.jpg",
404
+ "file:///path/to/frame4.jpg",
405
+ ],
406
+ "fps": 1.0,
407
+ },
408
+ {"type": "text", "text": "Descreva este vídeo."},
409
+ ],
410
+ }
411
+ ]
412
+ # Mensagens contendo um vídeo e uma consulta em texto
413
+ messages = [
414
+ {
415
+ "role": "user",
416
+ "content": [
417
+ {
418
+ "type": "video",
419
+ "video": "file:///path/to/video1.mp4",
420
+ "max_pixels": 360 * 420,
421
+ "fps": 1.0,
422
+ },
423
+ {"type": "text", "text": "Descreva este vídeo."},
424
+ ],
425
+ }
426
+ ]
427
+
428
+ # Preparação para inferência
429
+ text = processor.apply_chat_template(
430
+ messages, tokenize=False, add_generation_prompt=True
431
+ )
432
+ image_inputs, video_inputs = process_vision_info(messages)
433
+ inputs = processor(
434
+ text=[text],
435
+ images=image_inputs,
436
+ videos=video_inputs,
437
+ padding=True,
438
+ return_tensors="pt",
439
+ )
440
+ inputs = inputs.to("cuda")
441
+
442
+ # Inferência
443
+ generated_ids = model.generate(**inputs, max_new_tokens=128)
444
+ generated_ids_trimmed = [
445
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
446
+ ]
447
+ output_text = processor.batch_decode(
448
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
449
+ )
450
+ print(output_text)
451
+ ```
452
+
453
+ </details>
454
+
455
+ <details>
456
+ <summary>Inferência em lote</summary>
457
+
458
+ ```python
459
+ # Mensagens de exemplo para inferência em lote
460
+ messages1 = [
461
+ {
462
+ "role": "user",
463
+ "content": [
464
+ {"type": "image", "image": "file:///path/to/image1.jpg"},
465
+ {"type": "image", "image": "file:///path/to/image2.jpg"},
466
+ {"type": "text", "text": "Quais são os elementos comuns nessas imagens?"},
467
+ ],
468
+ }
469
+ ]
470
+ messages2 = [
471
+ {"role": "system", "content": "Você é um assistente útil."},
472
+ {"role": "user", "content": "Quem é você?"}
473
+ ]
474
+ # Combinar mensagens para processamento em lote
475
+ messages = [messages1, messages1]
476
+
477
+ # Preparação para inferência em lote
478
+ texts = [
479
+ processor.apply_chat_template(msg, tokenize=False, add_generation_prompt=True)
480
+ for msg in messages
481
+ ]
482
+ image_inputs, video_inputs = process_vision_info(messages)
483
+ inputs = processor(
484
+ text=texts,
485
+ images=image_inputs,
486
+ videos=video_inputs,
487
+ padding=True,
488
+ return_tensors="pt",
489
+ )
490
+ inputs = inputs.to("cuda")
491
+
492
+ # Inferência em lote
493
+ generated_ids = model.generate(**inputs, max_new_tokens=128)
494
+ generated_ids_trimmed = [
495
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
496
+ ]
497
+ output_texts = processor.batch_decode(
498
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
499
+ )
500
+ print(output_texts)
501
+ ```
502
+
503
+ </details>
504
+
505
+
506
+ ## **Limitações do Modelo**
507
+
508
+ 🔇 **Sem suporte para áudio**
509
+ 📅 **Base de dados limitada até junho de 2023**
510
+ 🔍 **Reconhecimento restrito de indivíduos e marcas**
511
+ 🧩 **Desempenho reduzido para tarefas complexas de múltiplas etapas**
512
+ 🔢 **Dificuldade na contagem precisa de objetos**
513
+ 📏 **Raciocínio espacial 3D limitado**
514
 
515
+ ---
516
 
517
+ ## Citations
518
+
519
+ ### Base Model Citation
520
+ ```bibtex
521
+ @article{Qwen2VL,
522
+ title={Qwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution},
523
+ author={Wang, Peng and Bai, Shuai and Tan, Sinan and Wang, Shijie and Fan, Zhihao and Bai, Jinze and Chen, Keqin and Liu, Xuejing and Wang, Jialin and Ge, Wenbin and Fan, Yang and Dang, Kai and Du, Mengfei and Ren, Xuancheng and Men, Rui and Liu, Dayiheng and Zhou, Chang and Zhou, Jingren and Lin, Junyang},
524
+ journal={arXiv preprint arXiv:2409.12191},
525
+ year={2024}
526
+ }
527
+
528
+ @article{Qwen-VL,
529
+ title={Qwen-VL: A Versatile Vision-Language Model for Understanding, Localization, Text Reading, and Beyond},
530
+ author={Bai, Jinze and Bai, Shuai and Yang, Shusheng and Wang, Shijie and Tan, Sinan and Wang, Peng and Lin, Junyang and Zhou, Chang and Zhou, Jingren},
531
+ journal={arXiv preprint arXiv:2308.12966},
532
+ year={2023}
533
+ }
534
+ ```