nooneshouldtouch commited on
Commit
6cdf49c
·
verified ·
1 Parent(s): 3f56989

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -33
app.py CHANGED
@@ -5,7 +5,7 @@ import tensorflow as tf
5
  from fastapi import FastAPI, File, UploadFile, Form, HTTPException
6
  from fastapi.responses import JSONResponse
7
  from fastapi.middleware.cors import CORSMiddleware
8
- from typing import Dict, Any
9
  from datetime import datetime, timezone
10
  from io import BytesIO
11
  from sqlalchemy import create_engine, Column, Integer, String, DateTime, ForeignKey, Text, func
@@ -93,38 +93,31 @@ def on_startup():
93
  fix_tf_gpu()
94
  prepare_model(approach=1)
95
 
96
- def run_detection_on_frame(frame: np.ndarray, upload_id: int, db: Session) -> np.ndarray:
97
- global model, input_shape, class_names
98
- ih, iw = frame.shape[:2]
99
- resized = letterbox_image(frame, input_shape)
100
- image_data = np.expand_dims(resized, 0) / 255.0
101
- prediction = model.predict(image_data)
102
- boxes = detection(
103
- prediction, None, len(class_names), (ih, iw), input_shape, 50, 0.3, 0.45, False
104
- )[0].numpy()
105
- workers, helmets, vests = [], [], []
106
- for box in boxes:
107
- x1, y1, x2, y2, score, cls_id = box
108
- x1, y1, x2, y2 = map(int, [x1, y1, x2, y2])
109
- cls_id = int(cls_id)
110
- label = class_names[cls_id]
111
- color = (0, 255, 0) if label == 'W' else (255, 0, 0) if label == 'H' else (0, 0, 255)
112
- cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
113
- cv2.putText(frame, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, color, 2)
114
- if label == 'W': workers.append((x1, y1, x2, y2))
115
- elif label == 'H': helmets.append((x1, y1, x2, y2))
116
- elif label == 'V': vests.append((x1, y1, x2, y2))
117
- upload_obj = db.query(Upload).filter(Upload.id == upload_id).first()
118
- if upload_obj:
119
- upload_obj.total_workers += len(workers)
120
- upload_obj.total_helmets += len(helmets)
121
- upload_obj.total_vests += len(vests)
122
- db.commit()
123
- return frame
124
 
125
  @app.post("/upload")
126
  async def upload_file(approach: int = Form(...), file: UploadFile = File(...)):
127
- global model
128
  db = SessionLocal()
129
  filename = file.filename
130
  filepath = os.path.join(UPLOAD_FOLDER, filename)
@@ -143,6 +136,7 @@ async def upload_file(approach: int = Form(...), file: UploadFile = File(...)):
143
  processed_filename = f"processed_{filename}"
144
  processed_path = os.path.join(PROCESSED_FOLDER, processed_filename)
145
  cv2.imwrite(processed_path, processed_img)
 
146
  db.refresh(upload_obj)
147
  db.close()
148
  return {
@@ -151,6 +145,6 @@ async def upload_file(approach: int = Form(...), file: UploadFile = File(...)):
151
  "total_workers": upload_obj.total_workers,
152
  "total_helmets": upload_obj.total_helmets,
153
  "total_vests": upload_obj.total_vests,
154
- "detected_items": upload_obj.worker_images.split(',') if upload_obj.worker_images else [],
155
- "processed_image": processed_path
156
- }
 
5
  from fastapi import FastAPI, File, UploadFile, Form, HTTPException
6
  from fastapi.responses import JSONResponse
7
  from fastapi.middleware.cors import CORSMiddleware
8
+ from typing import Dict, Any, List
9
  from datetime import datetime, timezone
10
  from io import BytesIO
11
  from sqlalchemy import create_engine, Column, Integer, String, DateTime, ForeignKey, Text, func
 
93
  fix_tf_gpu()
94
  prepare_model(approach=1)
95
 
96
+ def generate_pdf(upload_id: int, total_workers: int, total_helmets: int, total_vests: int) -> str:
97
+ pdf_path = os.path.join(PROCESSED_FOLDER, f"report_{upload_id}.pdf")
98
+ doc = SimpleDocTemplate(pdf_path, pagesize=A4)
99
+ styles = getSampleStyleSheet()
100
+ elements = []
101
+ elements.append(Paragraph("Industrial Safety Detection Report", styles["Title"]))
102
+ elements.append(Spacer(1, 12))
103
+ data = [["Total Workers", total_workers],
104
+ ["Total Helmets Detected", total_helmets],
105
+ ["Total Vests Detected", total_vests]]
106
+ table = Table(data, colWidths=[200, 100])
107
+ table.setStyle(TableStyle([
108
+ ('BACKGROUND', (0, 0), (-1, 0), colors.grey),
109
+ ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
110
+ ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
111
+ ('FONTNAME', (0, 0), (-1, -1), 'Helvetica-Bold'),
112
+ ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
113
+ ('BACKGROUND', (0, 1), (-1, -1), colors.beige),
114
+ ]))
115
+ elements.append(table)
116
+ doc.build(elements)
117
+ return pdf_path
 
 
 
 
 
 
118
 
119
  @app.post("/upload")
120
  async def upload_file(approach: int = Form(...), file: UploadFile = File(...)):
 
121
  db = SessionLocal()
122
  filename = file.filename
123
  filepath = os.path.join(UPLOAD_FOLDER, filename)
 
136
  processed_filename = f"processed_{filename}"
137
  processed_path = os.path.join(PROCESSED_FOLDER, processed_filename)
138
  cv2.imwrite(processed_path, processed_img)
139
+ pdf_path = generate_pdf(upload_id, upload_obj.total_workers, upload_obj.total_helmets, upload_obj.total_vests)
140
  db.refresh(upload_obj)
141
  db.close()
142
  return {
 
145
  "total_workers": upload_obj.total_workers,
146
  "total_helmets": upload_obj.total_helmets,
147
  "total_vests": upload_obj.total_vests,
148
+ "processed_image": processed_path,
149
+ "pdf_report": pdf_path
150
+ }