vkbajoria commited on
Commit
8ec5b8f
1 Parent(s): 8471818

add app.py

Browse files
Files changed (1) hide show
  1. app.py +124 -0
app.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from PIL import Image, ImageDraw, ImageFont
3
+ import scipy.io.wavfile as wavfile
4
+
5
+ # Use a pipeline as a high-level helper
6
+ from transformers import pipeline
7
+
8
+
9
+ narrator = pipeline("text-to-speech", model="kakao-enterprise/vits-ljs")
10
+ object_detector = pipeline("object-detection",model="facebook/detr-resnet-50")
11
+
12
+
13
+ # Define the function to generate audio from text
14
+ def generate_audio(text):
15
+ # Generate the narrated text
16
+ narrated_text = narrator(text)
17
+
18
+ # Save the audio to a WAV file
19
+ wavfile.write("output.wav", rate=narrated_text["sampling_rate"],
20
+ data=narrated_text["audio"][0])
21
+
22
+ # Return the path to the saved audio file
23
+ return "output.wav"
24
+
25
+ # Could you please write me a python code that will take list of detection object as an input and it will give the response that will include all the objects (labels) provided in the input. For example if the input is like this: [{'score': 0.9996405839920044, 'label': 'person', 'box': {'xmin': 435, 'ymin': 282, 'xmax': 636, 'ymax': 927}}, {'score': 0.9995879530906677, 'label': 'dog', 'box': {'xmin': 570, 'ymin': 694, 'xmax': 833, 'ymax': 946}}]
26
+ # The output should be, This pictuture contains 1 person and 1 dog. If there are multiple objects, do not add 'and' between every objects but 'and' should be at the end only
27
+
28
+
29
+ def read_objects(detection_objects):
30
+ # Initialize counters for each object label
31
+ object_counts = {}
32
+
33
+ # Count the occurrences of each label
34
+ for detection in detection_objects:
35
+ label = detection['label']
36
+ if label in object_counts:
37
+ object_counts[label] += 1
38
+ else:
39
+ object_counts[label] = 1
40
+
41
+ # Generate the response string
42
+ response = "This picture contains"
43
+ labels = list(object_counts.keys())
44
+ for i, label in enumerate(labels):
45
+ response += f" {object_counts[label]} {label}"
46
+ if object_counts[label] > 1:
47
+ response += "s"
48
+ if i < len(labels) - 2:
49
+ response += ","
50
+ elif i == len(labels) - 2:
51
+ response += " and"
52
+
53
+ response += "."
54
+
55
+ return response
56
+
57
+
58
+
59
+ def draw_bounding_boxes(image, detections, font_path=None, font_size=20):
60
+ """
61
+ Draws bounding boxes on the given image based on the detections.
62
+ :param image: PIL.Image object
63
+ :param detections: List of detection results, where each result is a dictionary containing
64
+ 'score', 'label', and 'box' keys. 'box' itself is a dictionary with 'xmin',
65
+ 'ymin', 'xmax', 'ymax'.
66
+ :param font_path: Path to the TrueType font file to use for text.
67
+ :param font_size: Size of the font to use for text.
68
+ :return: PIL.Image object with bounding boxes drawn.
69
+ """
70
+ # Make a copy of the image to draw on
71
+ draw_image = image.copy()
72
+ draw = ImageDraw.Draw(draw_image)
73
+
74
+ # Load custom font or default font if path not provided
75
+ if font_path:
76
+ font = ImageFont.truetype(font_path, font_size)
77
+ else:
78
+ # When font_path is not provided, load default font but it's size is fixed
79
+ font = ImageFont.load_default()
80
+ # Increase font size workaround by using a TTF font file, if needed, can download and specify the path
81
+
82
+ for detection in detections:
83
+ box = detection['box']
84
+ xmin = box['xmin']
85
+ ymin = box['ymin']
86
+ xmax = box['xmax']
87
+ ymax = box['ymax']
88
+
89
+ # Draw the bounding box
90
+ draw.rectangle([(xmin, ymin), (xmax, ymax)], outline="red", width=3)
91
+
92
+ # Optionally, you can also draw the label and score
93
+ label = detection['label']
94
+ score = detection['score']
95
+ text = f"{label} {score:.2f}"
96
+
97
+ # Draw text with background rectangle for visibility
98
+ if font_path: # Use the custom font with increased size
99
+ text_size = draw.textbbox((xmin, ymin), text, font=font)
100
+ else:
101
+ # Calculate text size using the default font
102
+ text_size = draw.textbbox((xmin, ymin), text)
103
+
104
+ draw.rectangle([(text_size[0], text_size[1]), (text_size[2], text_size[3])], fill="red")
105
+ draw.text((xmin, ymin), text, fill="white", font=font)
106
+
107
+ return draw_image
108
+
109
+
110
+ def detect_object(image):
111
+ raw_image = image
112
+ output = object_detector(raw_image)
113
+ processed_image = draw_bounding_boxes(raw_image, output)
114
+ natural_text = read_objects(output)
115
+ processed_audio = generate_audio(natural_text)
116
+ return processed_image, processed_audio
117
+
118
+
119
+ demo = gr.Interface(fn=detect_object,
120
+ inputs=[gr.Image(label="Select Image",type="pil")],
121
+ outputs=[gr.Image(label="Processed Image", type="pil"), gr.Audio(label="Generated Audio")],
122
+ title="@GenAILearniverse Project 7: Object Detector with Audio",
123
+ description="THIS APPLICATION WILL BE USED TO HIGHLIGHT OBJECTS AND GIVES AUDIO DESCRIPTION FOR THE PROVIDED INPUT IMAGE.")
124
+ demo.launch()