HarshanaLF commited on
Commit
71dfc01
·
verified ·
1 Parent(s): 114bb56

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -0
app.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import BlipProcessor, BlipForConditionalGeneration, pipeline
3
+
4
+ # Load the image captioning model and tokenizer
5
+ caption_model_name = "Salesforce/blip-image-captioning-large"
6
+ caption_processor = BlipProcessor.from_pretrained(caption_model_name)
7
+ caption_model = BlipForConditionalGeneration.from_pretrained(caption_model_name)
8
+
9
+ # Load the emotion analysis model
10
+ emotion_model_name = "SamLowe/roberta-base-go_emotions"
11
+ emotion_classifier = pipeline("text-classification", model=emotion_model_name)
12
+
13
+ def generate_caption_and_analyze_emotions(image):
14
+ try:
15
+ # Preprocess the image for caption generation
16
+ caption_inputs = caption_processor(images=image, return_tensors="pt")
17
+
18
+ # Generate caption using the caption model
19
+ caption_ids = caption_model.generate(**caption_inputs)
20
+
21
+ # Decode the output caption
22
+ decoded_caption = caption_processor.decode(caption_ids[0], skip_special_tokens=True)
23
+
24
+ # Perform emotion analysis on the generated caption
25
+ results = emotion_classifier(decoded_caption)
26
+ sentiment_label = results[0]['label']
27
+ if sentiment_label == 'neutral':
28
+ sentiment_text = "Sentiment of the image is"
29
+ else:
30
+ sentiment_text = "Sentiment of the image shows"
31
+
32
+ final_output = f"This image shows '{decoded_caption}' and {sentiment_text} {sentiment_label}."
33
+ return final_output
34
+ except Exception as e:
35
+ return f"An error occurred: {e}"
36
+
37
+ # Define the Gradio interface using the new API
38
+ inputs = gr.Image(label="Upload an image")
39
+ outputs = gr.Textbox(label="Sentiment Analysis")
40
+
41
+ # Create the Gradio app
42
+ app = gr.Interface(fn=generate_caption_and_analyze_emotions, inputs=inputs, outputs=outputs)
43
+
44
+ # Launch the Gradio app
45
+ if __name__ == "__main__":
46
+ app.launch()