kusumakar commited on
Commit
c598532
·
1 Parent(s): d976bcb

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -0
app.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ import streamlit as st
3
+ from transformers import GPT2Tokenizer, GPT2LMHeadModel
4
+ from transformers import AutoTokenizer, VisionEncoderDecoderModel, ViTFeatureExtractor
5
+
6
+ # Load the Model,feature extractor and tokenizer
7
+ model = VisionEncoderDecoderModel.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
8
+ extractor = ViTFeatureExtractor.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
9
+ tokeniser = AutoTokenizer.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
10
+
11
+ def generate_captions(image):
12
+ generated_caption = tokeniser.decode(model.generate(extractor(image, return_tensors="pt").pixel_values.to("cpu"))[0])
13
+ sentence = generated_caption
14
+ text_to_remove = "<|endoftext|>"
15
+ generated_caption = sentence.replace(text_to_remove, "")
16
+ return generated_caption
17
+
18
+ # Load the pre-trained model and tokenizer
19
+ model_name = "gpt2"
20
+ tokenizer = GPT2Tokenizer.from_pretrained(model_name)
21
+ model = GPT2LMHeadModel.from_pretrained(model_name)
22
+
23
+ # Define the Streamlit app
24
+ def generate_paragraph(prompt):
25
+ # Tokenize the prompt
26
+ input_ids = tokenizer.encode(prompt, return_tensors="pt")
27
+
28
+ # Generate the paragraph
29
+ output = model.generate(input_ids, max_length=200, num_return_sequences=1, early_stopping=True)
30
+
31
+ # Decode the generated output into text
32
+ paragraph = tokenizer.decode(output[0], skip_special_tokens=True)
33
+ return paragraph
34
+
35
+ # Streamlit app
36
+ def main():
37
+ # Set Streamlit app title and description
38
+ st.title("Paragraph Generation From Context of an Image")
39
+ st.subheader("Upload the Image to generate a paragraph.")
40
+
41
+ # create file uploader
42
+ uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
43
+
44
+ # check if file has been uploaded
45
+ if uploaded_file is not None:
46
+ # load the image
47
+ image = Image.open(uploaded_file).convert("RGB")
48
+
49
+ # context as prompt
50
+ prompt = generate_captions(uploaded_file)
51
+ st.write("The Context is:", prompt)
52
+
53
+ # display the image
54
+ st.image(uploaded_file)
55
+
56
+ generated_paragraph = generate_paragraph(prompt)
57
+
58
+ st.write(generated_paragraph)
59
+
60
+ if __name__ == "__main__":
61
+ main()