Update app.py
Browse files
app.py
CHANGED
@@ -1,45 +1,30 @@
|
|
1 |
-
from transformers import ViTFeatureExtractor, ViTForImageClassification
|
2 |
-
from PIL import Image
|
3 |
-
import requests
|
4 |
import gradio as gr
|
5 |
-
import
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
inputs=inp,
|
35 |
-
outputs=out,
|
36 |
-
fn=inference,
|
37 |
-
cache_examples=False)
|
38 |
-
|
39 |
-
button.click(fn=inference,
|
40 |
-
inputs=inp,
|
41 |
-
outputs=out)
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
demo.launch(share=True)
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
import requests
|
3 |
+
from io import BytesIO
|
4 |
+
from PIL import Image
|
5 |
+
import torch
|
6 |
+
from transformers import GPT2LMHeadModel, GPT2Tokenizer
|
7 |
+
|
8 |
+
# Load GPT-2 model and tokenizer
|
9 |
+
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
|
10 |
+
model = GPT2LMHeadModel.from_pretrained('gpt2')
|
11 |
+
|
12 |
+
def generate_caption(image):
|
13 |
+
# Preprocess image
|
14 |
+
response = requests.get(image)
|
15 |
+
img = Image.open(BytesIO(response.content)).convert('RGB')
|
16 |
+
img = img.resize((224, 224))
|
17 |
+
|
18 |
+
# Generate caption using GPT-2
|
19 |
+
input_text = "This is an image of " + tokenizer.decode(tokenizer.encode(image)) + ". "
|
20 |
+
input_ids = tokenizer.encode(input_text, return_tensors='pt')
|
21 |
+
output = model.generate(input_ids=input_ids, max_length=200, do_sample=True)
|
22 |
+
caption = tokenizer.decode(output[0], skip_special_tokens=True)
|
23 |
+
|
24 |
+
return caption
|
25 |
+
|
26 |
+
# Create Gradio interface
|
27 |
+
inputs = gr.inputs.Image()
|
28 |
+
outputs = gr.outputs.Textbox()
|
29 |
+
|
30 |
+
gr.Interface(fn=generate_caption, inputs=inputs, outputs=outputs, title='Image Captioning with GPT-2', description='Upload an image and get a detailed caption generated by GPT-2.').launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|