ankitdwivedi31 commited on
Commit
4c84885
·
verified ·
1 Parent(s): b83bf4a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -0
app.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ import gradio as gr
4
+ from PIL import Image, ImageDraw, ImageFont
5
+ from transformers import pipeline
6
+ import scipy.io.wavfile as wavfile
7
+ import numpy as np
8
+
9
+ object_detector = pipeline("object-detection", model="facebook/detr-resnet-50")
10
+ Narrator = pipeline("text-to-speech", model="kakao-enterprise/vits-ljs")
11
+ # model_path = "C:/Users/ankitdwivedi/OneDrive - Adobe/Desktop/NLP Projects/Video to Text Summarization/Model/models--facebook--detr-resnet-50/snapshots/1d5f47bd3bdd2c4bbfa585418ffe6da5028b4c0b"
12
+
13
+ # tts_model_path = "C:/Users/ankitdwivedi/OneDrive - Adobe/Desktop/NLP Projects/Video to Text Summarization/Model/models--kakao-enterprise--vits-ljs/snapshots/3bcb8321394f671bd948ebf0d086d694dda95464"
14
+
15
+ # object_detector = pipeline("object-detection", model=model_path)
16
+
17
+ # Narrator = pipeline("text-to-speech", model=tts_model_path)
18
+
19
+ ##read the image file
20
+ # raw_image =Image.open("C:/Users/ankitdwivedi/OneDrive - Adobe/Desktop/NLP Projects/Video to Text Summarization/Image_Processing/918oQOaXZTL._AC_UF1000,1000_QL80_.jpg")
21
+ # output = object_detector(raw_image)
22
+ #print(output)
23
+
24
+ # def generate_audio(text):
25
+ # Narrated_Text = Narrator(text)
26
+ # wavfile.write("fine_tuned_audio.wav", rate = Narrated_Text["sampling_rate"], data = Narrated_Text["audio"][0])
27
+ # return "output.wav"
28
+
29
+ def generate_audio(text):
30
+ Narrated_Text = Narrator(text)
31
+ audio_data = np.array(Narrated_Text["audio"][0])
32
+ sampling_rate = Narrated_Text["sampling_rate"]
33
+ wavfile.write("generated_audio.wav", rate=sampling_rate, data=audio_data)
34
+ return "generated_audio.wav"
35
+
36
+ def read_objects(detection_objects):
37
+ # Initialize counters for each object label
38
+ object_counts = {}
39
+
40
+ # Count the occurrences of each label
41
+ for detection in detection_objects:
42
+ label = detection['label']
43
+ if label in object_counts:
44
+ object_counts[label] += 1
45
+ else:
46
+ object_counts[label] = 1
47
+
48
+ # Generate the response string
49
+ response = "This picture contains"
50
+ labels = list(object_counts.keys())
51
+ for i, label in enumerate(labels):
52
+ response += f" {object_counts[label]} {label}"
53
+ if object_counts[label] > 1:
54
+ response += "s"
55
+ if i < len(labels) - 2:
56
+ response += ","
57
+ elif i == len(labels) - 2:
58
+ response += " and"
59
+
60
+ response += "."
61
+
62
+ return response
63
+
64
+ def draw_bounding_boxes(image, detections, font_path=None, font_size=20):
65
+ """
66
+ Draws bounding boxes on the given image based on the detections.
67
+ :param image: PIL.Image object
68
+ :param detections: List of detection results, where each result is a dictionary containing
69
+ 'score', 'label', and 'box' keys. 'box' itself is a dictionary with 'xmin',
70
+ 'ymin', 'xmax', 'ymax'.
71
+ :param font_path: Path to the TrueType font file to use for text.
72
+ :param font_size: Size of the font to use for text.
73
+ :return: PIL.Image object with bounding boxes drawn.
74
+ """
75
+ # Make a copy of the image to draw on
76
+ draw_image = image.copy()
77
+ draw = ImageDraw.Draw(draw_image)
78
+
79
+ # Load custom font or default font if path not provided
80
+ if font_path:
81
+ font = ImageFont.truetype(font_path, font_size)
82
+ else:
83
+ # When font_path is not provided, load default font but it's size is fixed
84
+ font = ImageFont.load_default()
85
+ # Increase font size workaround by using a TTF font file, if needed, can download and specify the path
86
+
87
+ for detection in detections:
88
+ box = detection['box']
89
+ xmin = box['xmin']
90
+ ymin = box['ymin']
91
+ xmax = box['xmax']
92
+ ymax = box['ymax']
93
+
94
+ # Draw the bounding box
95
+ draw.rectangle([(xmin, ymin), (xmax, ymax)], outline="red", width=3)
96
+
97
+ # Optionally, you can also draw the label and score
98
+ label = detection['label']
99
+ score = detection['score']
100
+ text = f"{label} {score:.2f}"
101
+
102
+ # Draw text with background rectangle for visibility
103
+ if font_path: # Use the custom font with increased size
104
+ text_size = draw.textbbox((xmin, ymin), text, font=font)
105
+ else:
106
+ # Calculate text size using the default font
107
+ text_size = draw.textbbox((xmin, ymin), text)
108
+
109
+ draw.rectangle([(text_size[0], text_size[1]), (text_size[2], text_size[3])], fill="red")
110
+ draw.text((xmin, ymin), text, fill="white", font=font)
111
+
112
+ return draw_image
113
+
114
+ def detect_object(image):
115
+ raw_image = image
116
+ output = object_detector(raw_image)
117
+ processed_image = draw_bounding_boxes(raw_image, output)
118
+ natural_text = read_objects(output)
119
+ processed_audio = generate_audio(natural_text)
120
+
121
+ return processed_image, processed_audio
122
+
123
+ demo = gr.Interface(fn=detect_object,
124
+ inputs=[gr.Image(label="Select Image",type="pil")],
125
+ outputs=[gr.Image(label="Processed Image", type="pil"),
126
+ gr.Audio(label="Generated_Audio")],
127
+ title="Project 7: Object Detector with Audio",
128
+ description="THIS APPLICATION WILL BE USED TO DETECT OBJECTS and Audio for objects mentioned INSIDE THE PROVIDED INPUT IMAGE.")
129
+ demo.launch()