capjamesg commited on
Commit
f61a028
·
1 Parent(s): c05df02

add project code

Browse files
Files changed (2) hide show
  1. app.py +201 -0
  2. requirements.txt +6 -0
app.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import concurrent.futures
3
+ import os
4
+ from io import BytesIO
5
+
6
+ import cv2
7
+ import gradio as gr
8
+ import numpy as np
9
+ import requests
10
+ import supervision as sv
11
+ from inference_sdk import InferenceHTTPClient
12
+ from openai import OpenAI
13
+
14
+ CLIENT = InferenceHTTPClient(
15
+ api_url="http://detect.roboflow.com",
16
+ api_key=os.environ["ROBOFLOW_API_KEY"],
17
+ )
18
+
19
+ openai_client = OpenAI()
20
+
21
+
22
+ def process_mask(region, task_id):
23
+ region = cv2.rotate(region, cv2.ROTATE_90_CLOCKWISE)
24
+
25
+ cv2.imwrite(f"region_{task_id}.jpg", region)
26
+
27
+ # change channels
28
+ region = cv2.cvtColor(region, cv2.COLOR_BGR2RGB)
29
+
30
+ base64_image = base64.b64encode(
31
+ BytesIO(cv2.imencode(".jpg", region)[1]).read()
32
+ ).decode("utf-8")
33
+
34
+ response = openai_client.chat.completions.create(
35
+ model="gpt-4-vision-preview",
36
+ messages=[
37
+ {
38
+ "role": "user",
39
+ "content": [
40
+ {
41
+ "type": "text",
42
+ "text": "Read the text on the book spine. Only say the book cover title and author if you can find them. Say the book that is most prominent. Return the format [title] [author], with no punctuation.",
43
+ },
44
+ {
45
+ "type": "image_url",
46
+ "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"},
47
+ },
48
+ ],
49
+ }
50
+ ],
51
+ max_tokens=300,
52
+ )
53
+
54
+ print(response.choices[0].message.content.rstrip("Title:").replace("\n", " "))
55
+
56
+ return response.choices[0].message.content.rstrip("Title:").replace("\n", " ")
57
+
58
+
59
+ def process_book_with_google_books(book):
60
+ response = requests.get(
61
+ f"https://www.googleapis.com/books/v1/volumes?q={book}",
62
+ headers={"User-Agent": "Mozilla/5.0"},
63
+ )
64
+ response = response.json()
65
+
66
+ isbn, author, link = "NULL", "NULL", "NULL"
67
+
68
+ try:
69
+ isbn = response["items"][0]["volumeInfo"]["industryIdentifiers"][0][
70
+ "identifier"
71
+ ]
72
+ if (
73
+ "volumeInfo" in response["items"][0]
74
+ and "authors" in response["items"][0]["volumeInfo"]
75
+ ):
76
+ author = response["items"][0]["volumeInfo"]["authors"][0]
77
+ link = response["items"][0]["volumeInfo"]["infoLink"]
78
+ except:
79
+ pass
80
+
81
+ return isbn, author, link
82
+
83
+
84
+ # define function that accepts an image
85
+ def detect_books(image):
86
+ # infer on a local image
87
+ results = CLIENT.infer(image, model_id="open-shelves/4")
88
+ results = sv.Detections.from_inference(results)
89
+
90
+ mask_annotator = sv.MaskAnnotator()
91
+ annotated_image = mask_annotator.annotate(scene=image, detections=results)
92
+
93
+ masks_isolated = []
94
+
95
+ masks_to_xyxys = sv.mask_to_xyxy(masks=results.mask)
96
+
97
+ polygons = [sv.mask_to_polygons(mask) for mask in results.mask]
98
+
99
+ for mask in results.mask:
100
+ masked_region = np.zeros_like(image)
101
+ masked_region[mask] = image[mask]
102
+ masks_isolated.append(masked_region)
103
+
104
+ print("Calculated masks...")
105
+
106
+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
107
+ tasks = [
108
+ executor.submit(process_mask, region, task_id)
109
+ for task_id, region in enumerate(masks_isolated)
110
+ ]
111
+ books = [task.result() for task in tasks]
112
+
113
+ print("Processed books...")
114
+
115
+ links = []
116
+
117
+ isbns = []
118
+ authors = []
119
+
120
+ with concurrent.futures.ThreadPoolExecutor() as executor:
121
+ tasks = [
122
+ executor.submit(process_book_with_google_books, book) for book in books
123
+ ]
124
+
125
+ for task in tasks:
126
+ isbn, author, link = task.result()
127
+ isbns.append(isbn)
128
+ authors.append(author)
129
+ links.append(link)
130
+
131
+ print("Processed books with Google Books...")
132
+
133
+ annotations = [
134
+ {
135
+ "title": title,
136
+ "author": author,
137
+ "isbn": isbn,
138
+ "polygons": [polygon.tolist() for polygon in polygon_list],
139
+ "xyxy": xyxy.tolist(),
140
+ "link": link,
141
+ }
142
+ for title, author, isbn, polygon_list, xyxy, link in zip(
143
+ books, authors, isbns, polygons, results.xyxy, links
144
+ )
145
+ if "sorry" not in title.lower() and "NULL" not in title
146
+ ]
147
+
148
+ width, height = image.shape[1], image.shape[0]
149
+
150
+ svg = f"""<div class="image-container"><img src="image.jpeg" height="{height}" width="{width}">
151
+
152
+ <svg width="{width}" height="{height}">"""
153
+
154
+ for annotation in annotations:
155
+ polygons = annotation["polygons"][0]
156
+ svg += f"""<polygon points="{', '.join([f'{x},{y}' for x, y in polygons])}" fill="transparent" stroke="red" stroke-width="2"
157
+ onclick="window.location.href='{annotation['link']}';"></polygon>"""
158
+
159
+ svg += "</svg>"
160
+ svg += """
161
+ <style>
162
+ .image-container {
163
+ position: relative;
164
+ height: HEIGHTpx;
165
+ width: WIDTHpx;
166
+ }
167
+ .image-container img, .image-container svg {
168
+ position: absolute;
169
+ left: 0;
170
+ top: 0;
171
+ width: 100%;
172
+ height: auto;
173
+ }
174
+ .image-container svg {
175
+ z-index: 1;
176
+ }
177
+ </style></div>""".replace(
178
+ "HEIGHT", str(height)
179
+ ).replace(
180
+ "WIDTH", str(width)
181
+ )
182
+
183
+ return annotated_image, books, isbns, svg
184
+
185
+
186
+ iface = gr.Interface(
187
+ fn=detect_books,
188
+ description="Use Open Shelves to detect books in an image. The model will return the annotated image with the detected books, the titles of the books, and the ISBNs of the books.",
189
+ inputs=gr.components.Image(label="Input Image"),
190
+ # outputs should be an image and a list of text
191
+ outputs=[
192
+ gr.components.Image(label="Annotated Image"),
193
+ gr.components.Textbox(label="Detected Books"),
194
+ gr.components.Textbox(label="ISBNs"),
195
+ gr.components.Textbox(label="SVG"),
196
+ ],
197
+ title="Open Shelves",
198
+ allow_flagging=False,
199
+ theme="huggingface",
200
+ )
201
+ iface.launch()
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio
2
+ requests
3
+ numpy
4
+ supervision
5
+ inference-sdk
6
+ openai