Nemil commited on
Commit
85f688c
β€’
1 Parent(s): b4527f0

Initial commit

Browse files
Files changed (2) hide show
  1. app.py +296 -0
  2. requirements.txt +1 -0
app.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoProcessor, AutoModelForCausalLM, BitsAndBytesConfig
2
+ import torch
3
+ from PIL import Image
4
+ import requests
5
+ import traceback
6
+
7
+ class Image2Text:
8
+ def __init__(self):
9
+ # Load the GIT coco model
10
+ preprocessor_git_large_coco = AutoProcessor.from_pretrained("microsoft/git-large-coco")
11
+ model_git_large_coco = AutoModelForCausalLM.from_pretrained("microsoft/git-large-coco")
12
+
13
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
14
+
15
+ self.preprocessor = preprocessor_git_large_coco
16
+ self.model = model_git_large_coco
17
+ self.model.to(self.device)
18
+
19
+
20
+ def image_description(
21
+ self,
22
+ image_url,
23
+ max_length=50,
24
+ temperature=0.1,
25
+ use_sample_image=False,
26
+ ):
27
+ """
28
+ Generate captions for the given image.
29
+
30
+ -----
31
+ Parameters
32
+ image_url: Image URL
33
+ The image to generate captions for.
34
+ max_length: int
35
+ The max length of the generated descriptions.
36
+
37
+ -----
38
+ Returns
39
+ str
40
+ The generated image description.
41
+ """
42
+ caption_git_large_coco = ""
43
+
44
+ if use_sample_image:
45
+ image_url = "http://images.cocodataset.org/val2017/000000039769.jpg"
46
+
47
+ image = Image.open(requests.get(image_url, stream=True).raw)
48
+
49
+ # Generate captions for the image using the GIT coco model
50
+ try:
51
+ caption_git_large_coco = self._generate_description(image, max_length, False).strip()
52
+ return caption_git_large_coco
53
+
54
+ except Exception as e:
55
+ print(e)
56
+ traceback.print_exc()
57
+
58
+
59
+ def _generate_description(
60
+ self,
61
+ image,
62
+ max_length=50,
63
+ use_float_16=False,
64
+ ):
65
+ """
66
+ Generate captions for the given image.
67
+
68
+ -----
69
+ Parameters
70
+ image: PIL.Image
71
+ The image to generate captions for.
72
+ max_length: int
73
+ The max length of the generated descriptions.
74
+ use_float_16: bool
75
+ Whether to use float16 precision. This can speed up inference, but may lead to worse results.
76
+
77
+ -----
78
+ Returns
79
+ str
80
+ The generated caption.
81
+ """
82
+ # inputs = preprocessor(image, return_tensors="pt").to(device)
83
+ pixel_values = self.preprocessor(images=image, return_tensors="pt").pixel_values.to(self.device)
84
+ generated_ids = self.model.generate(
85
+ pixel_values=pixel_values,
86
+ max_length=max_length,
87
+ )
88
+ generated_caption = self.preprocessor.batch_decode(generated_ids, skip_special_tokens=True)[0]
89
+ return generated_caption
90
+
91
+ import json
92
+ import os
93
+ from pprint import pprint
94
+
95
+ import bitsandbytes as bnb
96
+ import pandas as pd
97
+
98
+ import torch
99
+ import torch.nn as nn
100
+ import transformers
101
+ from datasets import load_dataset
102
+ from huggingface_hub import notebook_login
103
+ from peft import (
104
+ LoraConfig ,
105
+ PeftConfig ,
106
+ PeftModel ,
107
+ get_peft_model ,
108
+ prepare_model_for_kbit_training,
109
+ )
110
+ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig, AutoConfig
111
+ from peft import LoraConfig, get_peft_model
112
+
113
+
114
+ os.environ["CUDA_VISIBLE_DEVICES"] = "0"
115
+
116
+ class Social_Media_Captioner:
117
+ def __init__(self, use_finetuned: bool=True, temp=0.1):
118
+ self.use_finetuned = use_finetuned
119
+ self.MODEL_NAME = "vilsonrodrigues/falcon-7b-instruct-sharded"
120
+ self.peft_model_name = "ayush-vatsal/caption_qlora_finetune"
121
+ self.model_loaded = False
122
+ self.device = "cuda:0"
123
+
124
+ self._load_model()
125
+
126
+ self.generation_config = self.model.generation_config
127
+ self.generation_config.max_new_tokens = 50
128
+ self.generation_config.temperature = temp
129
+ self.generation_config.top_p = 0.7
130
+ self.generation_config.num_return_sequences = 1
131
+ self.generation_config.pad_token_id = self.tokenizer.eos_token_id
132
+ self.generation_config.eos_token_id = self.tokenizer.eos_token_id
133
+
134
+ self.cache: list[dict] = [] # [{"image_decription": "A man", "caption": ["A man"]}]
135
+
136
+
137
+ def _load_model(self):
138
+ try:
139
+ self.bnb_config = BitsAndBytesConfig(
140
+ load_in_4bit = True,
141
+ bnb_4bit_use_double_quant = True,
142
+ bnb_4bit_quant_type= "nf4",
143
+ bnb_4bit_compute_dtype=torch.bfloat16,
144
+ )
145
+ self.model = AutoModelForCausalLM.from_pretrained(
146
+ self.MODEL_NAME,
147
+ device_map = "auto",
148
+ trust_remote_code = True,
149
+ quantization_config = self.bnb_config
150
+ )
151
+
152
+ # Defining the tokenizers
153
+ self.tokenizer = AutoTokenizer.from_pretrained(self.MODEL_NAME)
154
+ self.tokenizer.pad_token = self.tokenizer.eos_token
155
+
156
+ if self.use_finetuned:
157
+ # LORA Config Model
158
+ self.lora_config = LoraConfig(
159
+ r=16,
160
+ lora_alpha=32,
161
+ target_modules=["query_key_value"],
162
+ lora_dropout=0.05,
163
+ bias="none",
164
+ task_type="CAUSAL_LM"
165
+ )
166
+ self.model = get_peft_model(self.model, self.lora_config)
167
+
168
+ # Fitting the adapters
169
+ self.peft_config = PeftConfig.from_pretrained(self.peft_model_name)
170
+ self.model = AutoModelForCausalLM.from_pretrained(
171
+ self.peft_config.base_model_name_or_path,
172
+ return_dict = True,
173
+ quantization_config = self.bnb_config,
174
+ device_map= "auto",
175
+ trust_remote_code = True
176
+ )
177
+ self.model = PeftModel.from_pretrained(self.model, self.peft_model_name)
178
+
179
+ # Defining the tokenizers
180
+ self.tokenizer = AutoTokenizer.from_pretrained(self.peft_config.base_model_name_or_path)
181
+ self.tokenizer.pad_token = self.tokenizer.eos_token
182
+
183
+ self.model_loaded = True
184
+ print("Model Loaded successfully")
185
+
186
+ except Exception as e:
187
+ print(e)
188
+ self.model_loaded = False
189
+
190
+
191
+ def inference(self, input_text: str, use_cached=True, cache_generation=True) -> str | None:
192
+ if not self.model_loaded:
193
+ raise Exception("Model not loaded")
194
+
195
+ try:
196
+ prompt = Social_Media_Captioner._prompt(input_text)
197
+ if use_cached:
198
+ for item in self.cache:
199
+ if item['image_description'] == input_text:
200
+ return item['caption']
201
+
202
+ encoding = self.tokenizer(prompt, return_tensors = "pt").to(self.device)
203
+ with torch.inference_mode():
204
+ outputs = self.model.generate(
205
+ input_ids = encoding.input_ids,
206
+ attention_mask = encoding.attention_mask,
207
+ generation_config = self.generation_config
208
+ )
209
+ generated_caption = (self.tokenizer.decode(outputs[0], skip_special_tokens=True).split('Caption: "')[-1]).split('"')[0]
210
+
211
+ if cache_generation:
212
+ for item in self.cache:
213
+ if item['image_description'] == input_text:
214
+ item['caption'].append(generated_caption)
215
+ break
216
+ else:
217
+ self.cache.append({
218
+ 'image_description': input_text,
219
+ 'caption': [generated_caption]
220
+ })
221
+
222
+ return generated_caption
223
+ except Exception as e:
224
+ print(e)
225
+ return None
226
+
227
+
228
+ def _prompt(input_text="A man walking alone in the road"):
229
+ if input_text is None:
230
+ raise Exception("Enter a valid input text to generate a valid prompt")
231
+
232
+ return f"""
233
+ Convert the given image description to a appropriate metaphoric caption
234
+ Description: {input_text}
235
+ Caption:
236
+ """.strip()
237
+
238
+ @staticmethod
239
+ def get_trainable_parameters(model):
240
+ trainable_params = 0
241
+ all_param = 0
242
+ for _, param in model.named_parameters():
243
+ all_param += param.numel()
244
+ if param.requires_grad:
245
+ trainable_params += param.numel()
246
+ return f"trainable_params: {trainable_params} || all_params: {all_param} || Percentage of trainable params: {100*trainable_params / all_param}"
247
+
248
+
249
+ def __repr__(self):
250
+ return f"""
251
+ Base Model Name: {self.MODEL_NAME}
252
+ PEFT Model Name: {self.peft_model_name}
253
+ Using PEFT Finetuned Model: {self.use_finetuned}
254
+ Model: {self.model}
255
+
256
+ ------------------------------------------------------------
257
+
258
+ {Social_Media_Captioner.get_trainable_parameters(self.model)}
259
+ """
260
+
261
+ class Captions:
262
+ def __init__(self, use_finetuned_LLM: bool=True, temp_LLM=0.1):
263
+ self.image_to_text = Image2Text()
264
+ self.LLM = Social_Media_Captioner(use_finetuned_LLM, temp_LLM)
265
+
266
+ def generate_captions(
267
+ self,
268
+ image,
269
+ image_url=None,
270
+ max_length_GIT=50,
271
+ temperature_GIT=0.1,
272
+ use_sample_image_GIT=False,
273
+ use_cached_LLM=True,
274
+ cache_generation_LLM=True
275
+ ):
276
+ if image_url:
277
+ image_description = self.image_to_text.image_description(image_url, max_length=max_length_GIT, temperature=temperature_GIT, use_sample_image=use_sample_image_GIT)
278
+ else:
279
+ image_description = self.image_to_text._generate_description(image, max_length=max_length_GIT)
280
+ captions = self.LLM.inference(image_description, use_cached=use_cached_LLM, cache_generation=cache_generation_LLM)
281
+ return captions
282
+
283
+ caption_generator = Captions()
284
+
285
+ import gradio as gr
286
+
287
+ def setup(image):
288
+ return caption_generator.generate_captions(image = image)
289
+
290
+ iface = gr.Interface(
291
+ fn=setup,
292
+ inputs=gr.inputs.Image(type="pil", label="Upload Image"),
293
+ outputs=gr.outputs.Textbox(label="Caption")
294
+ )
295
+
296
+ iface.launch()
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ gradio==3.36.0