banao-tech commited on
Commit
ab332bc
·
verified ·
1 Parent(s): 13c1ab1

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +43 -32
main.py CHANGED
@@ -6,6 +6,7 @@ import os
6
  import logging
7
  from PIL import Image
8
  import torch
 
9
 
10
  # Existing imports
11
  from utils import (
@@ -58,11 +59,17 @@ class ProcessResponse(BaseModel):
58
  parsed_content_list: str
59
  label_coordinates: str
60
 
61
- def process(image_input: Image.Image, box_threshold: float, iou_threshold: float) -> ProcessResponse:
62
  image_save_path = "imgs/saved_image_demo.png"
63
  os.makedirs(os.path.dirname(image_save_path), exist_ok=True)
64
- image_input.save(image_save_path)
65
-
 
 
 
 
 
 
66
  image = Image.open(image_save_path)
67
  box_overlay_ratio = image.size[0] / 3200
68
  draw_bbox_config = {
@@ -72,40 +79,46 @@ def process(image_input: Image.Image, box_threshold: float, iou_threshold: float
72
  "thickness": max(int(3 * box_overlay_ratio), 1),
73
  }
74
 
75
- ocr_bbox_rslt, is_goal_filtered = check_ocr_box(
 
 
 
76
  image_save_path,
77
- display_img=False,
78
- output_bb_format="xyxy",
79
- goal_filtering=None,
80
- easyocr_args={"paragraph": False, "text_threshold": 0.9},
81
- use_paddleocr=True,
82
  )
83
  text, ocr_bbox = ocr_bbox_rslt
84
 
85
- dino_labled_img, label_coordinates, parsed_content_list = get_som_labeled_img(
86
- image_save_path,
87
- yolo_model,
88
- BOX_TRESHOLD=box_threshold,
89
- output_coord_in_ratio=True,
90
- ocr_bbox=ocr_bbox,
91
- draw_bbox_config=draw_bbox_config,
92
- caption_model_processor=caption_model_processor,
93
- ocr_text=text,
94
- iou_threshold=iou_threshold,
95
- )
 
 
 
 
 
 
 
96
 
97
- # Log parsed_content_list to inspect its structure before joining
98
- logger.info(f"Parsed content list before join: {parsed_content_list}")
99
-
100
- # Ensure parsed_content_list is a list of strings, not dictionaries
101
- parsed_content_list_str = "\n".join([str(item) for item in parsed_content_list])
102
 
 
103
  image = Image.open(io.BytesIO(base64.b64decode(dino_labled_img)))
104
- print("Finish processing")
105
 
106
- # Convert the image to base64
107
  buffered = io.BytesIO()
108
- image.save(buffered, format="PNG")
109
  img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
110
 
111
  return ProcessResponse(
@@ -114,7 +127,6 @@ def process(image_input: Image.Image, box_threshold: float, iou_threshold: float
114
  label_coordinates=str(label_coordinates),
115
  )
116
 
117
-
118
  @app.post("/process_image", response_model=ProcessResponse)
119
  async def process_image(
120
  image_file: UploadFile = File(...),
@@ -132,7 +144,7 @@ async def process_image(
132
  if not image_input:
133
  raise ValueError("Image input is empty or invalid.")
134
 
135
- response = process(image_input, box_threshold, iou_threshold)
136
 
137
  # Ensure the response contains an image
138
  if not response.image:
@@ -145,5 +157,4 @@ async def process_image(
145
  logger.error(f"Error processing image: {e}")
146
  import traceback
147
  traceback.print_exc()
148
- raise HTTPException(status_code=500, detail=str(e))
149
-
 
6
  import logging
7
  from PIL import Image
8
  import torch
9
+ import asyncio # Import asyncio for asynchronous operations
10
 
11
  # Existing imports
12
  from utils import (
 
59
  parsed_content_list: str
60
  label_coordinates: str
61
 
62
+ async def process(image_input: Image.Image, box_threshold: float, iou_threshold: float) -> ProcessResponse:
63
  image_save_path = "imgs/saved_image_demo.png"
64
  os.makedirs(os.path.dirname(image_save_path), exist_ok=True)
65
+
66
+ # Save the image asynchronously
67
+ loop = asyncio.get_event_loop()
68
+ await loop.run_in_executor(None, image_input.save, image_save_path)
69
+
70
+ logger.info(f"Saved image for processing: {image_save_path}")
71
+
72
+ # Open image and prepare it for further processing
73
  image = Image.open(image_save_path)
74
  box_overlay_ratio = image.size[0] / 3200
75
  draw_bbox_config = {
 
79
  "thickness": max(int(3 * box_overlay_ratio), 1),
80
  }
81
 
82
+ # OCR and YOLO box processing (run in a thread pool to avoid blocking the event loop)
83
+ ocr_bbox_rslt, is_goal_filtered = await loop.run_in_executor(
84
+ None,
85
+ check_ocr_box,
86
  image_save_path,
87
+ False, # display_img
88
+ "xyxy", # output_bb_format
89
+ None, # goal_filtering
90
+ {"paragraph": False, "text_threshold": 0.9}, # easyocr_args
91
+ True, # use_paddleocr
92
  )
93
  text, ocr_bbox = ocr_bbox_rslt
94
 
95
+ # Process image and get result (run in a thread pool)
96
+ try:
97
+ dino_labled_img, label_coordinates, parsed_content_list = await loop.run_in_executor(
98
+ None,
99
+ get_som_labeled_img,
100
+ image_save_path,
101
+ yolo_model,
102
+ box_threshold, # BOX_TRESHOLD
103
+ True, # output_coord_in_ratio
104
+ ocr_bbox, # ocr_bbox
105
+ draw_bbox_config, # draw_bbox_config
106
+ caption_model_processor, # caption_model_processor
107
+ text, # ocr_text
108
+ iou_threshold, # iou_threshold
109
+ )
110
+ except Exception as e:
111
+ logger.error(f"Error during labeling and captioning: {e}")
112
+ raise
113
 
114
+ logger.info("Finished processing image with YOLO and captioning.")
 
 
 
 
115
 
116
+ # Convert the image to base64 string
117
  image = Image.open(io.BytesIO(base64.b64decode(dino_labled_img)))
118
+ parsed_content_list_str = "\n".join(parsed_content_list)
119
 
 
120
  buffered = io.BytesIO()
121
+ await loop.run_in_executor(None, image.save, buffered, "PNG")
122
  img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
123
 
124
  return ProcessResponse(
 
127
  label_coordinates=str(label_coordinates),
128
  )
129
 
 
130
  @app.post("/process_image", response_model=ProcessResponse)
131
  async def process_image(
132
  image_file: UploadFile = File(...),
 
144
  if not image_input:
145
  raise ValueError("Image input is empty or invalid.")
146
 
147
+ response = await process(image_input, box_threshold, iou_threshold)
148
 
149
  # Ensure the response contains an image
150
  if not response.image:
 
157
  logger.error(f"Error processing image: {e}")
158
  import traceback
159
  traceback.print_exc()
160
+ raise HTTPException(status_code=500, detail=str(e))