Spaces:
Sleeping
Sleeping
updated
Browse files
main.py
CHANGED
@@ -1,333 +1,337 @@
|
|
1 |
-
from fastapi import FastAPI, File, UploadFile, Response, HTTPException
|
2 |
-
from fastapi.responses import JSONResponse, FileResponse
|
3 |
-
from fastapi.middleware.cors import CORSMiddleware
|
4 |
-
from PIL import Image
|
5 |
-
import io
|
6 |
-
import requests
|
7 |
-
import sqlite3
|
8 |
-
from pydantic import BaseModel, EmailStr
|
9 |
-
from typing import List, Optional
|
10 |
-
|
11 |
-
|
12 |
-
from pathlib import Path
|
13 |
-
from model import YOLOModel
|
14 |
-
import shutil
|
15 |
-
|
16 |
-
from openpyxl import Workbook
|
17 |
-
from openpyxl.drawing.image import Image as ExcelImage
|
18 |
-
from openpyxl.styles import Alignment
|
19 |
-
import os
|
20 |
-
|
21 |
-
yolo = YOLOModel()
|
22 |
-
|
23 |
-
UPLOAD_FOLDER = Path("./uploads")
|
24 |
-
UPLOAD_FOLDER.mkdir(exist_ok=True)
|
25 |
-
|
26 |
-
app = FastAPI()
|
27 |
-
|
28 |
-
cropped_images_dir = "cropped_images"
|
29 |
-
|
30 |
-
# Initialize SQLite database
|
31 |
-
def init_db():
|
32 |
-
conn = sqlite3.connect('users.db')
|
33 |
-
c = conn.cursor()
|
34 |
-
c.execute('''
|
35 |
-
CREATE TABLE IF NOT EXISTS users (
|
36 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
37 |
-
firstName TEXT NOT NULL,
|
38 |
-
lastName TEXT NOT NULL,
|
39 |
-
country TEXT,
|
40 |
-
number TEXT, -- Phone number stored as TEXT to allow various formats
|
41 |
-
email TEXT UNIQUE NOT NULL, -- Email should be unique and non-null
|
42 |
-
password TEXT NOT NULL -- Password will be stored as a string (hashed ideally)
|
43 |
-
)
|
44 |
-
''')
|
45 |
-
conn.commit()
|
46 |
-
conn.close()
|
47 |
-
|
48 |
-
init_db()
|
49 |
-
|
50 |
-
class UserSignup(BaseModel):
|
51 |
-
firstName: str
|
52 |
-
lastName: str
|
53 |
-
country: str
|
54 |
-
number: str
|
55 |
-
email: EmailStr
|
56 |
-
password: str
|
57 |
-
|
58 |
-
class UserLogin(BaseModel):
|
59 |
-
email: str
|
60 |
-
password: str
|
61 |
-
|
62 |
-
@app.post("/signup")
|
63 |
-
async def signup(user_data: UserSignup):
|
64 |
-
try:
|
65 |
-
conn = sqlite3.connect('users.db')
|
66 |
-
c = conn.cursor()
|
67 |
-
|
68 |
-
# Check if user already exists
|
69 |
-
c.execute("SELECT * FROM users WHERE email = ?", (user_data.email,))
|
70 |
-
if c.fetchone():
|
71 |
-
raise HTTPException(status_code=400, detail="Email already registered")
|
72 |
-
|
73 |
-
# Insert new user
|
74 |
-
c.execute("""
|
75 |
-
INSERT INTO users (firstName, lastName, country, number, email, password)
|
76 |
-
VALUES (?, ?, ?, ?, ?, ?)
|
77 |
-
""", (user_data.firstName, user_data.lastName, user_data.country, user_data.number, user_data.email, user_data.password))
|
78 |
-
|
79 |
-
conn.commit()
|
80 |
-
conn.close()
|
81 |
-
|
82 |
-
return {"message": "User registered successfully", "email": user_data.email}
|
83 |
-
except Exception as e:
|
84 |
-
raise HTTPException(status_code=500, detail=str(e))
|
85 |
-
|
86 |
-
@app.post("/login")
|
87 |
-
async def login(user_data: UserLogin):
|
88 |
-
try:
|
89 |
-
conn = sqlite3.connect('users.db')
|
90 |
-
c = conn.cursor()
|
91 |
-
|
92 |
-
# Find user
|
93 |
-
c.execute("SELECT * FROM users WHERE email = ? AND password = ?",
|
94 |
-
(user_data.email, user_data.password))
|
95 |
-
user = c.fetchone()
|
96 |
-
|
97 |
-
conn.close()
|
98 |
-
|
99 |
-
if not user:
|
100 |
-
raise HTTPException(status_code=401, detail="Invalid credentials")
|
101 |
-
|
102 |
-
return {
|
103 |
-
"message": "Login successful",
|
104 |
-
"user": {
|
105 |
-
"firstName": user[1],
|
106 |
-
"lastName": user[2],
|
107 |
-
"email": user[3]
|
108 |
-
}
|
109 |
-
}
|
110 |
-
except Exception as e:
|
111 |
-
raise HTTPException(status_code=500, detail=str(e))
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
@app.post("/upload")
|
116 |
-
async def upload_image(image: UploadFile = File(...)):
|
117 |
-
# print(f'\n\t\tUPLOADED!!!!')
|
118 |
-
try:
|
119 |
-
file_path = UPLOAD_FOLDER / image.filename
|
120 |
-
with file_path.open("wb") as buffer:
|
121 |
-
shutil.copyfileobj(image.file, buffer)
|
122 |
-
# print(f'Starting to pass into model, {file_path}')
|
123 |
-
# Perform YOLO inference
|
124 |
-
predictions = yolo.predict(str(file_path))
|
125 |
-
print(f'\n\n\n{predictions}\n\n\ \n\t\t\t\tare predictions')
|
126 |
-
# Clean up uploaded file
|
127 |
-
file_path.unlink() # Remove file after processing
|
128 |
-
return JSONResponse(content={"items": predictions})
|
129 |
-
|
130 |
-
|
131 |
-
except Exception as e:
|
132 |
-
return JSONResponse(content={"error": str(e)}, status_code=500)
|
133 |
-
|
134 |
-
|
135 |
-
@app.get("/download_cropped_image/{image_idx}")
|
136 |
-
def download_cropped_image(image_idx: int):
|
137 |
-
cropped_image_path = cropped_images_dir / f"crop_{image_idx}.jpg"
|
138 |
-
if cropped_image_path.exists():
|
139 |
-
return FileResponse(cropped_image_path, media_type="image/jpeg")
|
140 |
-
return JSONResponse(content={"error": "Cropped image not found"}, status_code=404)
|
141 |
-
|
142 |
-
|
143 |
-
def cleanup_images(directory: str):
|
144 |
-
"""Remove all images in the directory."""
|
145 |
-
for file in Path(directory).glob("*"):
|
146 |
-
file.unlink()
|
147 |
-
'''
|
148 |
-
|
149 |
-
@app.post("/generate-excel/")
|
150 |
-
async def generate_excel(predictions: list):
|
151 |
-
# Create an Excel workbook
|
152 |
-
workbook = Workbook()
|
153 |
-
sheet = workbook.active
|
154 |
-
sheet.title = "Predictions"
|
155 |
-
|
156 |
-
# Add headers
|
157 |
-
headers = ["Category", "Confidence", "Predicted Brand", "Price", "Details", "Detected Text", "Image"]
|
158 |
-
sheet.append(headers)
|
159 |
-
|
160 |
-
for idx, prediction in enumerate(predictions):
|
161 |
-
# Extract details from the prediction
|
162 |
-
category = prediction["category"]
|
163 |
-
confidence = prediction["confidence"]
|
164 |
-
predicted_brand = prediction["predicted_brand"]
|
165 |
-
price = prediction["price"]
|
166 |
-
details = prediction["details"]
|
167 |
-
detected_text = prediction["detected_text"]
|
168 |
-
cropped_image_path = prediction["image_path"]
|
169 |
-
|
170 |
-
# Append data row
|
171 |
-
sheet.append([category, confidence, predicted_brand, price, details, detected_text])
|
172 |
-
|
173 |
-
# Add the image to the Excel file (if it exists)
|
174 |
-
if os.path.exists(cropped_image_path):
|
175 |
-
img = ExcelImage(cropped_image_path)
|
176 |
-
img.width, img.height = 50, 50 # Resize image to fit into the cell
|
177 |
-
sheet.add_image(img, f"G{idx + 2}") # Place in the "Image" column
|
178 |
-
|
179 |
-
excel_file_path = "predictions_with_images.xlsx"
|
180 |
-
workbook.save(excel_file_path)
|
181 |
-
|
182 |
-
# Cleanup after saving
|
183 |
-
cleanup_images(cropped_images_dir)
|
184 |
-
|
185 |
-
# Serve the Excel file as a response
|
186 |
-
return FileResponse(
|
187 |
-
excel_file_path,
|
188 |
-
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
189 |
-
filename="predictions_with_images.xlsx"
|
190 |
-
)
|
191 |
-
|
192 |
-
'''
|
193 |
-
|
194 |
-
# Define the Prediction model
|
195 |
-
class Prediction(BaseModel):
|
196 |
-
category: Optional[str]
|
197 |
-
confidence: Optional[float]
|
198 |
-
predicted_brand: Optional[str]
|
199 |
-
price: Optional[str]
|
200 |
-
details: Optional[str]
|
201 |
-
detected_text: Optional[str]
|
202 |
-
image_url: Optional[str]
|
203 |
-
image_path: Optional[str]
|
204 |
-
|
205 |
-
|
206 |
-
@app.post("/generate-excel/")
|
207 |
-
async def generate_excel(predictions: List[Prediction]):
|
208 |
-
print('Generate excel called')
|
209 |
-
|
210 |
-
# Create an Excel workbook
|
211 |
-
workbook = Workbook()
|
212 |
-
sheet = workbook.active
|
213 |
-
sheet.title = "Predictions"
|
214 |
-
|
215 |
-
# Add headers
|
216 |
-
headers = ["Category", "Confidence", "Predicted Brand", "Price", "Image URL", "Details", "Detected Text", ]
|
217 |
-
sheet.append(headers)
|
218 |
-
|
219 |
-
# Set header style and alignment
|
220 |
-
for cell in sheet[1]:
|
221 |
-
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
222 |
-
sheet.row_dimensions[1].height = 30 # Adjust header row height
|
223 |
-
|
224 |
-
# Set column widths based on data type
|
225 |
-
column_widths = {
|
226 |
-
"A": 20, # Category
|
227 |
-
"B": 15, # Confidence
|
228 |
-
"C": 40, # Predicted Brand
|
229 |
-
"D": 15, # Price
|
230 |
-
"E": 50, # Image URL
|
231 |
-
"F": 30, # Details
|
232 |
-
"G": 30 # Detected Text
|
233 |
-
}
|
234 |
-
for col, width in column_widths.items():
|
235 |
-
sheet.column_dimensions[col].width = width
|
236 |
-
|
237 |
-
# Add prediction rows
|
238 |
-
for idx, prediction in enumerate(predictions):
|
239 |
-
row_index = idx + 2 # Start from the second row
|
240 |
-
|
241 |
-
# Add data to the row
|
242 |
-
sheet.append([
|
243 |
-
prediction.category,
|
244 |
-
prediction.confidence,
|
245 |
-
prediction.predicted_brand,
|
246 |
-
prediction.price,
|
247 |
-
prediction.image_url,
|
248 |
-
prediction.details,
|
249 |
-
prediction.detected_text,
|
250 |
-
|
251 |
-
])
|
252 |
-
|
253 |
-
# Adjust row height for multiline text
|
254 |
-
sheet.row_dimensions[row_index].height = 180 # Default height for rows
|
255 |
-
|
256 |
-
# Wrap text in all cells of the row
|
257 |
-
for col_idx in range(1, 8): # Columns A to G
|
258 |
-
cell = sheet.cell(row=row_index, column=col_idx)
|
259 |
-
cell.alignment = Alignment(wrap_text=True, vertical="top")
|
260 |
-
|
261 |
-
# Add image if the path exists
|
262 |
-
if os.path.exists(prediction.image_path):
|
263 |
-
img = ExcelImage(prediction.image_path)
|
264 |
-
img.width, img.height = 160, 160 # Resize image to fit into the cell
|
265 |
-
img_cell = f"G{row_index}" # Image column
|
266 |
-
sheet.add_image(img, img_cell)
|
267 |
-
|
268 |
-
# Save the Excel file
|
269 |
-
excel_file_path = "predictions_with_images.xlsx"
|
270 |
-
workbook.save(excel_file_path)
|
271 |
-
|
272 |
-
# Serve the Excel file as a response
|
273 |
-
return FileResponse(
|
274 |
-
excel_file_path,
|
275 |
-
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
276 |
-
filename="predictions_with_images.xlsx"
|
277 |
-
)
|
278 |
-
'''
|
279 |
-
|
280 |
-
@app.post("/generate-excel/")
|
281 |
-
async def generate_excel(predictions: list):
|
282 |
-
print('Generate excel called')
|
283 |
-
# Create an Excel workbook
|
284 |
-
workbook = Workbook()
|
285 |
-
sheet = workbook.active
|
286 |
-
sheet.title = "Predictions"
|
287 |
-
|
288 |
-
# Add headers
|
289 |
-
headers = ["Category", "Confidence", "Predicted Brand", "Price", "Details", "Detected Text", "Image URL"]
|
290 |
-
sheet.append(headers)
|
291 |
-
|
292 |
-
# Format the header row
|
293 |
-
for cell in sheet[1]:
|
294 |
-
cell.alignment = Alignment(horizontal="center", vertical="center")
|
295 |
-
|
296 |
-
for idx, prediction in enumerate(predictions):
|
297 |
-
# Extract details from the prediction
|
298 |
-
category = prediction["category"]
|
299 |
-
confidence = prediction["confidence"]
|
300 |
-
predicted_brand = prediction["predicted_brand"]
|
301 |
-
price = prediction["price"]
|
302 |
-
details = prediction["details"]
|
303 |
-
detected_text = prediction["detected_text"]
|
304 |
-
image_url = prediction["image_url"] # URL to the image
|
305 |
-
cropped_image_path = prediction["image_path"] # Path to local image file for Excel embedding
|
306 |
-
|
307 |
-
# Append data row
|
308 |
-
sheet.append([category, confidence, predicted_brand, price, details, detected_text, image_url])
|
309 |
-
|
310 |
-
# If the image path exists, add the image to the Excel file
|
311 |
-
if os.path.exists(cropped_image_path):
|
312 |
-
img = ExcelImage(cropped_image_path)
|
313 |
-
img.width, img.height = 50, 50 # Resize image to fit into the cell
|
314 |
-
sheet.add_image(img, f"G{idx + 2}") # Place in the "Image" column
|
315 |
-
|
316 |
-
excel_file_path = "predictions_with_images.xlsx"
|
317 |
-
workbook.save(excel_file_path)
|
318 |
-
|
319 |
-
# Serve the Excel file as a response
|
320 |
-
return FileResponse(
|
321 |
-
excel_file_path,
|
322 |
-
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
323 |
-
filename="predictions_with_images.xlsx"
|
324 |
-
)
|
325 |
-
'''
|
326 |
-
|
327 |
-
# code to accept the localhost to get images from
|
328 |
-
app.add_middleware(
|
329 |
-
CORSMiddleware,
|
330 |
-
allow_origins=["
|
331 |
-
allow_methods=["*"],
|
332 |
-
allow_headers=["*"],
|
333 |
-
)
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, File, UploadFile, Response, HTTPException
|
2 |
+
from fastapi.responses import JSONResponse, FileResponse
|
3 |
+
from fastapi.middleware.cors import CORSMiddleware
|
4 |
+
from PIL import Image
|
5 |
+
import io
|
6 |
+
import requests
|
7 |
+
import sqlite3
|
8 |
+
from pydantic import BaseModel, EmailStr
|
9 |
+
from typing import List, Optional
|
10 |
+
|
11 |
+
|
12 |
+
from pathlib import Path
|
13 |
+
from model import YOLOModel
|
14 |
+
import shutil
|
15 |
+
|
16 |
+
from openpyxl import Workbook
|
17 |
+
from openpyxl.drawing.image import Image as ExcelImage
|
18 |
+
from openpyxl.styles import Alignment
|
19 |
+
import os
|
20 |
+
|
21 |
+
yolo = YOLOModel()
|
22 |
+
|
23 |
+
UPLOAD_FOLDER = Path("./uploads")
|
24 |
+
UPLOAD_FOLDER.mkdir(exist_ok=True)
|
25 |
+
|
26 |
+
app = FastAPI()
|
27 |
+
|
28 |
+
cropped_images_dir = "cropped_images"
|
29 |
+
|
30 |
+
# Initialize SQLite database
|
31 |
+
def init_db():
|
32 |
+
conn = sqlite3.connect('users.db')
|
33 |
+
c = conn.cursor()
|
34 |
+
c.execute('''
|
35 |
+
CREATE TABLE IF NOT EXISTS users (
|
36 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
37 |
+
firstName TEXT NOT NULL,
|
38 |
+
lastName TEXT NOT NULL,
|
39 |
+
country TEXT,
|
40 |
+
number TEXT, -- Phone number stored as TEXT to allow various formats
|
41 |
+
email TEXT UNIQUE NOT NULL, -- Email should be unique and non-null
|
42 |
+
password TEXT NOT NULL -- Password will be stored as a string (hashed ideally)
|
43 |
+
)
|
44 |
+
''')
|
45 |
+
conn.commit()
|
46 |
+
conn.close()
|
47 |
+
|
48 |
+
init_db()
|
49 |
+
|
50 |
+
class UserSignup(BaseModel):
|
51 |
+
firstName: str
|
52 |
+
lastName: str
|
53 |
+
country: str
|
54 |
+
number: str
|
55 |
+
email: EmailStr
|
56 |
+
password: str
|
57 |
+
|
58 |
+
class UserLogin(BaseModel):
|
59 |
+
email: str
|
60 |
+
password: str
|
61 |
+
|
62 |
+
@app.post("/signup")
|
63 |
+
async def signup(user_data: UserSignup):
|
64 |
+
try:
|
65 |
+
conn = sqlite3.connect('users.db')
|
66 |
+
c = conn.cursor()
|
67 |
+
|
68 |
+
# Check if user already exists
|
69 |
+
c.execute("SELECT * FROM users WHERE email = ?", (user_data.email,))
|
70 |
+
if c.fetchone():
|
71 |
+
raise HTTPException(status_code=400, detail="Email already registered")
|
72 |
+
|
73 |
+
# Insert new user
|
74 |
+
c.execute("""
|
75 |
+
INSERT INTO users (firstName, lastName, country, number, email, password)
|
76 |
+
VALUES (?, ?, ?, ?, ?, ?)
|
77 |
+
""", (user_data.firstName, user_data.lastName, user_data.country, user_data.number, user_data.email, user_data.password))
|
78 |
+
|
79 |
+
conn.commit()
|
80 |
+
conn.close()
|
81 |
+
|
82 |
+
return {"message": "User registered successfully", "email": user_data.email}
|
83 |
+
except Exception as e:
|
84 |
+
raise HTTPException(status_code=500, detail=str(e))
|
85 |
+
|
86 |
+
@app.post("/login")
|
87 |
+
async def login(user_data: UserLogin):
|
88 |
+
try:
|
89 |
+
conn = sqlite3.connect('users.db')
|
90 |
+
c = conn.cursor()
|
91 |
+
|
92 |
+
# Find user
|
93 |
+
c.execute("SELECT * FROM users WHERE email = ? AND password = ?",
|
94 |
+
(user_data.email, user_data.password))
|
95 |
+
user = c.fetchone()
|
96 |
+
|
97 |
+
conn.close()
|
98 |
+
|
99 |
+
if not user:
|
100 |
+
raise HTTPException(status_code=401, detail="Invalid credentials")
|
101 |
+
|
102 |
+
return {
|
103 |
+
"message": "Login successful",
|
104 |
+
"user": {
|
105 |
+
"firstName": user[1],
|
106 |
+
"lastName": user[2],
|
107 |
+
"email": user[3]
|
108 |
+
}
|
109 |
+
}
|
110 |
+
except Exception as e:
|
111 |
+
raise HTTPException(status_code=500, detail=str(e))
|
112 |
+
|
113 |
+
|
114 |
+
|
115 |
+
@app.post("/upload")
|
116 |
+
async def upload_image(image: UploadFile = File(...)):
|
117 |
+
# print(f'\n\t\tUPLOADED!!!!')
|
118 |
+
try:
|
119 |
+
file_path = UPLOAD_FOLDER / image.filename
|
120 |
+
with file_path.open("wb") as buffer:
|
121 |
+
shutil.copyfileobj(image.file, buffer)
|
122 |
+
# print(f'Starting to pass into model, {file_path}')
|
123 |
+
# Perform YOLO inference
|
124 |
+
predictions = yolo.predict(str(file_path))
|
125 |
+
print(f'\n\n\n{predictions}\n\n\ \n\t\t\t\tare predictions')
|
126 |
+
# Clean up uploaded file
|
127 |
+
file_path.unlink() # Remove file after processing
|
128 |
+
return JSONResponse(content={"items": predictions})
|
129 |
+
|
130 |
+
|
131 |
+
except Exception as e:
|
132 |
+
return JSONResponse(content={"error": str(e)}, status_code=500)
|
133 |
+
|
134 |
+
|
135 |
+
@app.get("/download_cropped_image/{image_idx}")
|
136 |
+
def download_cropped_image(image_idx: int):
|
137 |
+
cropped_image_path = cropped_images_dir / f"crop_{image_idx}.jpg"
|
138 |
+
if cropped_image_path.exists():
|
139 |
+
return FileResponse(cropped_image_path, media_type="image/jpeg")
|
140 |
+
return JSONResponse(content={"error": "Cropped image not found"}, status_code=404)
|
141 |
+
|
142 |
+
|
143 |
+
def cleanup_images(directory: str):
|
144 |
+
"""Remove all images in the directory."""
|
145 |
+
for file in Path(directory).glob("*"):
|
146 |
+
file.unlink()
|
147 |
+
'''
|
148 |
+
|
149 |
+
@app.post("/generate-excel/")
|
150 |
+
async def generate_excel(predictions: list):
|
151 |
+
# Create an Excel workbook
|
152 |
+
workbook = Workbook()
|
153 |
+
sheet = workbook.active
|
154 |
+
sheet.title = "Predictions"
|
155 |
+
|
156 |
+
# Add headers
|
157 |
+
headers = ["Category", "Confidence", "Predicted Brand", "Price", "Details", "Detected Text", "Image"]
|
158 |
+
sheet.append(headers)
|
159 |
+
|
160 |
+
for idx, prediction in enumerate(predictions):
|
161 |
+
# Extract details from the prediction
|
162 |
+
category = prediction["category"]
|
163 |
+
confidence = prediction["confidence"]
|
164 |
+
predicted_brand = prediction["predicted_brand"]
|
165 |
+
price = prediction["price"]
|
166 |
+
details = prediction["details"]
|
167 |
+
detected_text = prediction["detected_text"]
|
168 |
+
cropped_image_path = prediction["image_path"]
|
169 |
+
|
170 |
+
# Append data row
|
171 |
+
sheet.append([category, confidence, predicted_brand, price, details, detected_text])
|
172 |
+
|
173 |
+
# Add the image to the Excel file (if it exists)
|
174 |
+
if os.path.exists(cropped_image_path):
|
175 |
+
img = ExcelImage(cropped_image_path)
|
176 |
+
img.width, img.height = 50, 50 # Resize image to fit into the cell
|
177 |
+
sheet.add_image(img, f"G{idx + 2}") # Place in the "Image" column
|
178 |
+
|
179 |
+
excel_file_path = "predictions_with_images.xlsx"
|
180 |
+
workbook.save(excel_file_path)
|
181 |
+
|
182 |
+
# Cleanup after saving
|
183 |
+
cleanup_images(cropped_images_dir)
|
184 |
+
|
185 |
+
# Serve the Excel file as a response
|
186 |
+
return FileResponse(
|
187 |
+
excel_file_path,
|
188 |
+
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
189 |
+
filename="predictions_with_images.xlsx"
|
190 |
+
)
|
191 |
+
|
192 |
+
'''
|
193 |
+
|
194 |
+
# Define the Prediction model
|
195 |
+
class Prediction(BaseModel):
|
196 |
+
category: Optional[str]
|
197 |
+
confidence: Optional[float]
|
198 |
+
predicted_brand: Optional[str]
|
199 |
+
price: Optional[str]
|
200 |
+
details: Optional[str]
|
201 |
+
detected_text: Optional[str]
|
202 |
+
image_url: Optional[str]
|
203 |
+
image_path: Optional[str]
|
204 |
+
|
205 |
+
|
206 |
+
@app.post("/generate-excel/")
|
207 |
+
async def generate_excel(predictions: List[Prediction]):
|
208 |
+
print('Generate excel called')
|
209 |
+
|
210 |
+
# Create an Excel workbook
|
211 |
+
workbook = Workbook()
|
212 |
+
sheet = workbook.active
|
213 |
+
sheet.title = "Predictions"
|
214 |
+
|
215 |
+
# Add headers
|
216 |
+
headers = ["Category", "Confidence", "Predicted Brand", "Price", "Image URL", "Details", "Detected Text", ]
|
217 |
+
sheet.append(headers)
|
218 |
+
|
219 |
+
# Set header style and alignment
|
220 |
+
for cell in sheet[1]:
|
221 |
+
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
222 |
+
sheet.row_dimensions[1].height = 30 # Adjust header row height
|
223 |
+
|
224 |
+
# Set column widths based on data type
|
225 |
+
column_widths = {
|
226 |
+
"A": 20, # Category
|
227 |
+
"B": 15, # Confidence
|
228 |
+
"C": 40, # Predicted Brand
|
229 |
+
"D": 15, # Price
|
230 |
+
"E": 50, # Image URL
|
231 |
+
"F": 30, # Details
|
232 |
+
"G": 30 # Detected Text
|
233 |
+
}
|
234 |
+
for col, width in column_widths.items():
|
235 |
+
sheet.column_dimensions[col].width = width
|
236 |
+
|
237 |
+
# Add prediction rows
|
238 |
+
for idx, prediction in enumerate(predictions):
|
239 |
+
row_index = idx + 2 # Start from the second row
|
240 |
+
|
241 |
+
# Add data to the row
|
242 |
+
sheet.append([
|
243 |
+
prediction.category,
|
244 |
+
prediction.confidence,
|
245 |
+
prediction.predicted_brand,
|
246 |
+
prediction.price,
|
247 |
+
prediction.image_url,
|
248 |
+
prediction.details,
|
249 |
+
prediction.detected_text,
|
250 |
+
|
251 |
+
])
|
252 |
+
|
253 |
+
# Adjust row height for multiline text
|
254 |
+
sheet.row_dimensions[row_index].height = 180 # Default height for rows
|
255 |
+
|
256 |
+
# Wrap text in all cells of the row
|
257 |
+
for col_idx in range(1, 8): # Columns A to G
|
258 |
+
cell = sheet.cell(row=row_index, column=col_idx)
|
259 |
+
cell.alignment = Alignment(wrap_text=True, vertical="top")
|
260 |
+
|
261 |
+
# Add image if the path exists
|
262 |
+
if os.path.exists(prediction.image_path):
|
263 |
+
img = ExcelImage(prediction.image_path)
|
264 |
+
img.width, img.height = 160, 160 # Resize image to fit into the cell
|
265 |
+
img_cell = f"G{row_index}" # Image column
|
266 |
+
sheet.add_image(img, img_cell)
|
267 |
+
|
268 |
+
# Save the Excel file
|
269 |
+
excel_file_path = "predictions_with_images.xlsx"
|
270 |
+
workbook.save(excel_file_path)
|
271 |
+
|
272 |
+
# Serve the Excel file as a response
|
273 |
+
return FileResponse(
|
274 |
+
excel_file_path,
|
275 |
+
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
276 |
+
filename="predictions_with_images.xlsx"
|
277 |
+
)
|
278 |
+
'''
|
279 |
+
|
280 |
+
@app.post("/generate-excel/")
|
281 |
+
async def generate_excel(predictions: list):
|
282 |
+
print('Generate excel called')
|
283 |
+
# Create an Excel workbook
|
284 |
+
workbook = Workbook()
|
285 |
+
sheet = workbook.active
|
286 |
+
sheet.title = "Predictions"
|
287 |
+
|
288 |
+
# Add headers
|
289 |
+
headers = ["Category", "Confidence", "Predicted Brand", "Price", "Details", "Detected Text", "Image URL"]
|
290 |
+
sheet.append(headers)
|
291 |
+
|
292 |
+
# Format the header row
|
293 |
+
for cell in sheet[1]:
|
294 |
+
cell.alignment = Alignment(horizontal="center", vertical="center")
|
295 |
+
|
296 |
+
for idx, prediction in enumerate(predictions):
|
297 |
+
# Extract details from the prediction
|
298 |
+
category = prediction["category"]
|
299 |
+
confidence = prediction["confidence"]
|
300 |
+
predicted_brand = prediction["predicted_brand"]
|
301 |
+
price = prediction["price"]
|
302 |
+
details = prediction["details"]
|
303 |
+
detected_text = prediction["detected_text"]
|
304 |
+
image_url = prediction["image_url"] # URL to the image
|
305 |
+
cropped_image_path = prediction["image_path"] # Path to local image file for Excel embedding
|
306 |
+
|
307 |
+
# Append data row
|
308 |
+
sheet.append([category, confidence, predicted_brand, price, details, detected_text, image_url])
|
309 |
+
|
310 |
+
# If the image path exists, add the image to the Excel file
|
311 |
+
if os.path.exists(cropped_image_path):
|
312 |
+
img = ExcelImage(cropped_image_path)
|
313 |
+
img.width, img.height = 50, 50 # Resize image to fit into the cell
|
314 |
+
sheet.add_image(img, f"G{idx + 2}") # Place in the "Image" column
|
315 |
+
|
316 |
+
excel_file_path = "predictions_with_images.xlsx"
|
317 |
+
workbook.save(excel_file_path)
|
318 |
+
|
319 |
+
# Serve the Excel file as a response
|
320 |
+
return FileResponse(
|
321 |
+
excel_file_path,
|
322 |
+
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
323 |
+
filename="predictions_with_images.xlsx"
|
324 |
+
)
|
325 |
+
'''
|
326 |
+
|
327 |
+
# code to accept the localhost to get images from
|
328 |
+
app.add_middleware(
|
329 |
+
CORSMiddleware,
|
330 |
+
allow_origins=["*"],
|
331 |
+
allow_methods=["*"],
|
332 |
+
allow_headers=["*"],
|
333 |
+
)
|
334 |
+
|
335 |
+
if __name__ == "__main__":
|
336 |
+
import uvicorn
|
337 |
+
uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=True)
|