cooldan commited on
Commit
266fe67
·
verified ·
1 Parent(s): 3cd4142

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -55
app.py CHANGED
@@ -31,9 +31,7 @@ os.environ['TMPDIR'] = '/app/temp'
31
  os.environ['HOME'] = '/app'
32
  os.environ['USER'] = 'app'
33
 
34
- # Force CPU mode for HF Spaces (no GPU available)
35
- os.environ['CUDA_VISIBLE_DEVICES'] = '' # Hide all GPUs
36
- os.environ['PADDLE_INFERENCE_BACKEND'] = 'cpu' # Force CPU backend
37
 
38
  # Create directories with proper permissions for all PaddleOCR models
39
  try:
@@ -386,7 +384,7 @@ def process_image(image_path, mode="fast"):
386
  # Use single OCR model (mode parameter kept for future use)
387
  logger.info(f"Processing image with OCR mode: {mode}")
388
 
389
- # Use ocr.predict() with single model (like ocr_api_server.py)
390
  result = ocr.predict(str(image_path))
391
 
392
  zones = []
@@ -428,53 +426,37 @@ def process_image(image_path, mode="fast"):
428
  else:
429
  text_orientation = 0
430
 
431
- # Enhanced orientation detection for 45° angles
432
- if text_orientation == 0: # Only analyze if PaddleOCR didn't detect rotation
433
- # Analyze polygon shape to detect 45° rotation
434
- if len(poly) >= 4:
435
- # Calculate the angle of the first edge
436
- edge1 = [poly[1][0] - poly[0][0], poly[1][1] - poly[0][1]]
437
- edge2 = [poly[2][0] - poly[1][0], poly[2][1] - poly[1][1]]
438
-
439
- # Calculate angle of first edge
440
- angle1 = math.degrees(math.atan2(edge1[1], edge1[0]))
441
- angle2 = math.degrees(math.atan2(edge2[1], edge2[0]))
442
-
443
- # Normalize angles to 0-360
444
- angle1 = (angle1 + 360) % 360
445
- angle2 = (angle2 + 360) % 360
446
-
447
- # Check for 45° patterns
448
- for angle in [angle1, angle2]:
449
- # Check for 45°, 135°, 225°, 315° (±10° tolerance)
450
- if (35 <= angle <= 55) or (125 <= angle <= 145) or (215 <= angle <= 235) or (305 <= angle <= 325):
451
- if 35 <= angle <= 55:
452
- text_orientation = 45
453
- elif 125 <= angle <= 145:
454
- text_orientation = 135
455
- elif 215 <= angle <= 235:
456
- text_orientation = 225
457
- elif 305 <= angle <= 325:
458
- text_orientation = 315
459
- print(f"Enhanced orientation detection: {text} -> {text_orientation}° (angle: {angle:.1f}°)")
460
- break
461
-
462
- zone = {
463
- "id": f"ocr_zone_{i}",
464
- "text": text,
465
- "confidence": float(score),
466
  "bbox": {
467
- "x1": int(x1), "y1": int(y1),
468
- "x2": int(x2), "y2": int(y2),
469
- "width": int(x2 - x1),
470
- "height": int(y2 - y1)
 
 
471
  },
472
- "polygon": poly,
473
- "text_orientation": text_orientation,
474
- "is_dimension": is_dimension_text(text),
475
- "tolerance_info": parse_tolerance(text)
476
- }
477
- zones.append(zone)
 
 
 
478
 
479
  # Create overlay image with bounding boxes
480
  overlay_path = create_overlay_image(image_path, zones)
@@ -501,17 +483,16 @@ async def startup_event():
501
  global ocr
502
  logger.info("Initializing PaddleOCR model...")
503
 
504
- # Single OCR instance (force CPU mode for HF Spaces)
505
  try:
506
- logger.info("Initializing PaddleOCR in CPU mode for HF Spaces...")
507
  ocr = PaddleOCR(
508
- use_gpu=False, # Force CPU mode for HF Spaces
509
  use_doc_orientation_classify=False, # Disable for better performance
510
  use_doc_unwarping=False,
511
  use_textline_orientation=True, # Enable text line orientation
512
  lang='en'
513
  )
514
- logger.info("PaddleOCR initialized successfully in CPU mode!")
515
  except Exception as error:
516
  logger.error(f"PaddleOCR initialization failed: {error}")
517
  raise
@@ -1042,5 +1023,4 @@ def find_lines_near_dimensions(zones, lines, max_distance=50):
1042
 
1043
  if __name__ == "__main__":
1044
  import uvicorn
1045
- uvicorn.run(app, host="0.0.0.0", port=8000)
1046
-
 
31
  os.environ['HOME'] = '/app'
32
  os.environ['USER'] = 'app'
33
 
34
+ # Let PaddleOCR auto-detect GPU/CPU (newer versions handle this automatically)
 
 
35
 
36
  # Create directories with proper permissions for all PaddleOCR models
37
  try:
 
384
  # Use single OCR model (mode parameter kept for future use)
385
  logger.info(f"Processing image with OCR mode: {mode}")
386
 
387
+ # Use ocr.predict() method (PaddleOCR 2.8+ API)
388
  result = ocr.predict(str(image_path))
389
 
390
  zones = []
 
426
  else:
427
  text_orientation = 0
428
 
429
+ # Calculate text dimensions
430
+ text_width = x2 - x1
431
+ text_height = y2 - y1
432
+
433
+ # Parse tolerance information
434
+ tolerance_info = parse_tolerance(text)
435
+
436
+ # Check if this looks like a dimension
437
+ is_dimension = is_dimension_text(text)
438
+
439
+ # Create zone with proper bbox format
440
+ zone = {
441
+ "text": text,
442
+ "confidence": score,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
443
  "bbox": {
444
+ "x1": int(x1),
445
+ "y1": int(y1),
446
+ "x2": int(x2),
447
+ "y2": int(y2),
448
+ "width": int(text_width),
449
+ "height": int(text_height)
450
  },
451
+ "orientation": text_orientation,
452
+ "rotation": text_orientation, # Keep for compatibility
453
+ "width": int(text_width),
454
+ "height": int(text_height),
455
+ "is_dimension": is_dimension,
456
+ "tolerance_info": tolerance_info
457
+ }
458
+
459
+ zones.append(zone)
460
 
461
  # Create overlay image with bounding boxes
462
  overlay_path = create_overlay_image(image_path, zones)
 
483
  global ocr
484
  logger.info("Initializing PaddleOCR model...")
485
 
486
+ # Single OCR instance (auto GPU detection for newer PaddleOCR)
487
  try:
488
+ logger.info("Initializing PaddleOCR with auto GPU detection...")
489
  ocr = PaddleOCR(
 
490
  use_doc_orientation_classify=False, # Disable for better performance
491
  use_doc_unwarping=False,
492
  use_textline_orientation=True, # Enable text line orientation
493
  lang='en'
494
  )
495
+ logger.info("PaddleOCR initialized successfully with auto GPU detection!")
496
  except Exception as error:
497
  logger.error(f"PaddleOCR initialization failed: {error}")
498
  raise
 
1023
 
1024
  if __name__ == "__main__":
1025
  import uvicorn
1026
+ uvicorn.run(app, host="0.0.0.0", port=8000)