Mr-Vicky-01 commited on
Commit
6364e8b
1 Parent(s): 1a117af

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -0
app.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ from transformers import BlipProcessor, BlipForConditionalGeneration
3
+ from langchain.llms import GooglePalm
4
+ from langchain import LLMChain, PromptTemplate
5
+ from gtts import gTTS
6
+ from IPython.display import Audio
7
+ import gradio as gr
8
+ import numpy as np
9
+ import os
10
+
11
+ # Load image captioning model
12
+ processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
13
+ model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
14
+
15
+ def generate_caption_from_image(image_path):
16
+ # Process the image and generate caption
17
+ raw_image = Image.open(image_path).convert("RGB")
18
+ inputs = processor(raw_image, return_tensors="pt")
19
+ out = model.generate(**inputs)
20
+ caption = processor.decode(out[0], skip_special_tokens=True)
21
+ return caption
22
+
23
+ def generate_story_from_caption(caption):
24
+ # Generate story based on caption
25
+ api_key = os.getenv("GOOGLE_API")
26
+ prompt_template = """You are a story teller;
27
+ You can generate a short story based on a simple narrative, the story should between 30 to 50 words;
28
+ CONTEXT: {scenario}
29
+ Story: """
30
+ PROMPT = PromptTemplate(template=prompt_template, input_variables=["scenario"])
31
+ llm_chain = LLMChain(prompt=PROMPT,
32
+ llm=GooglePalm(google_api_key=api_key, temperature=0.8))
33
+ scenario = caption
34
+ story = llm_chain.run(scenario)
35
+ return story
36
+
37
+ def text_to_speech(text):
38
+ # Convert text to speech
39
+ tts = gTTS(text=text, lang='en')
40
+ tts.save("output.mp3")
41
+ return "output.mp3"
42
+
43
+ def generate_story_from_image(image_input):
44
+ input_image = Image.fromarray(image_input)
45
+ input_image.save("input_image.jpg")
46
+ image_path = 'input_image.jpg'
47
+ caption = generate_caption_from_image(image_path)
48
+ story = generate_story_from_caption(caption)
49
+ audio = text_to_speech(story)
50
+ return audio
51
+
52
+
53
+ # Define the input and output components
54
+ inputs = gr.Image(label="Image")
55
+ outputs = gr.Audio(label="Story Audio")
56
+
57
+ # Create the Gradio interface
58
+ gr.Interface(fn=generate_story_from_image, inputs=inputs, outputs=outputs, title="Story Teller").launch(debug=True,share=True)