File size: 2,485 Bytes
b5e959f
 
 
 
 
5149f5a
 
 
6d700e4
5149f5a
 
 
 
f9f9974
5149f5a
 
 
 
 
 
 
 
 
b5e959f
 
6d700e4
b5e959f
 
 
 
 
 
 
 
 
6d700e4
b5e959f
 
6d700e4
b5e959f
 
5149f5a
 
b5e959f
5149f5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d700e4
 
 
5149f5a
 
 
1
2
3
4
5
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import os
import openai
api_key = os.environ.get('OPENAI_API_KEY')
openai.api_key = api_key

import numpy as np
from PIL import Image
import streamlit as st
from transformers import AutoTokenizer, ViTFeatureExtractor, VisionEncoderDecoderModel, GPT2Tokenizer, GPT2LMHeadModel

# Directory path to the saved model on Google Drive
model = VisionEncoderDecoderModel.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
feature_extractor = ViTFeatureExtractor.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
tokenizer = AutoTokenizer.from_pretrained("nlpconnect/vit-gpt2-image-captioning")

def generate_captions(image):
    image = Image.open(image).convert("RGB")
    generated_caption = tokenizer.decode(model.generate(feature_extractor(image, return_tensors="pt").pixel_values.to("cpu"))[0])
    sentence = generated_caption
    text_to_remove = "<|endoftext|>"
    generated_caption = sentence.replace(text_to_remove, "")
    return generated_caption

def generate_paragraph(caption):
    prompt = "Generate a paragraph based on the following caption: " + caption

    # Make the API call to GPT-3
    response = openai.Completion.create(
        engine='text-davinci-003',  # Specify the GPT-3 model
        prompt=prompt,
        max_tokens=200,  # Adjust the desired length of the generated text
        n = 1,  # Set the number of completions to generate
        stop=None,  # Specify an optional stop sequence
        temperature=0.7  # Adjust the temperature for randomness (between 0 and 1)
    )

    # Extract the generated text from the API response
    generated_text = response.choices[0].text.strip()
    
    return generated_text

# create the Streamlit app
def app():
    st.title('Image from your Side, Detailed description from my site')

    st.write('Upload an image to see what we have in store.')

    # create file uploader
    uploaded_file = st.file_uploader("Got You Covered, Upload your wish!, magic on the Way! ", type=["jpg", "jpeg", "png"])

    # check if file has been uploaded
    if uploaded_file is not None:
        # load the image
        image = Image.open(uploaded_file).convert("RGB")

        # Image Captions
        string = generate_captions(uploaded_file)

        st.image(image, caption='The Uploaded File')
        st.write("First is first captions for your Photo : ", string)

        generated_paragraph = generate_paragraph(string)

        st.write(generated_paragraph)
# run the app
if __name__ == '__main__':
    app()