|
from dotenv import find_dotenv, load_dotenv |
|
from transformers import pipeline |
|
from langchain import PromptTemplate, LLMChain, OpenAI |
|
import requests |
|
import os |
|
import streamlit as st |
|
|
|
load_dotenv(find_dotenv()) |
|
HF_API_KEY=os.getenv("HF_API_KEY") |
|
|
|
|
|
def img2text(url): |
|
image_to_text_model = pipeline("image-to-text", model="Salesforce/blip-image-captioning-large") |
|
text = image_to_text_model(url)[0]["generated_text"] |
|
|
|
print(text) |
|
return text |
|
|
|
|
|
|
|
def generate_description(caption): |
|
template = """ |
|
You are a story teller; |
|
You can generate a short story based on a simple narrative, the story should be no more than 30 words; |
|
CONTEXT: {caption} |
|
STORY; |
|
""" |
|
|
|
prompt = PromptTemplate(template=template, input_variables=["caption"]) |
|
|
|
desc_llm = LLMChain(llm=OpenAI(model_name="gpt-4", temperature=1), prompt=prompt, verbose=True) |
|
description = desc_llm.predict(caption=caption).replace('"', '') |
|
|
|
print(description) |
|
return description |
|
|
|
|
|
|
|
|
|
def text2speech(message): |
|
API_URL = "https://api-inference.huggingface.co/models/espnet/kan-bayashi_ljspeech_vits" |
|
headers = {"Authorization": f"Bearer {HF_API_KEY}"} |
|
payload = { |
|
"inputs": message |
|
} |
|
|
|
response = requests.post(API_URL, headers=headers, json=payload) |
|
with open('audio.flac', 'wb') as file: |
|
file.write(response.content) |
|
|
|
|
|
def main(): |
|
st.set_page_config(page_title="image-to-caption-to-summary", page_icon="π") |
|
st.header("Image to caption to summary") |
|
uploaded_file = st.file_uploader("Choose an image", type=['png', 'jpg']) |
|
|
|
if uploaded_file is not None: |
|
print(uploaded_file) |
|
bytes_data = uploaded_file.getvalue() |
|
with open(uploaded_file.name, "wb") as file: |
|
file.write(bytes_data) |
|
|
|
st.image(uploaded_file, caption="Uploaded Image", use_column_width=True) |
|
|
|
st.text('Processing img2text...') |
|
caption = img2text(uploaded_file.name) |
|
with st.expander("caption"): |
|
st.write(caption) |
|
|
|
st.text('Generating description of given image...') |
|
description = generate_description(caption) |
|
with st.expander("Description"): |
|
st.write(story) |
|
|
|
st.text('Processing text2speech...') |
|
text2speech(story) |
|
st.audio("audio.flac") |
|
|
|
if __name__ == '__main__': |
|
main() |