codic commited on
Commit
11d8d89
·
verified ·
1 Parent(s): 84ffd92

adding qr code scann -- before was working

Browse files
Files changed (1) hide show
  1. app.py +57 -11
app.py CHANGED
@@ -11,6 +11,7 @@ import pandas as pd
11
  import io
12
  import re
13
  import traceback
 
14
 
15
  # Configure logging
16
  logging.basicConfig(level=logging.INFO)
@@ -29,14 +30,59 @@ except Exception as e:
29
 
30
  # Get a random color (used for drawing bounding boxes, if needed)
31
  def get_random_color():
32
- return tuple(np.random.randint(0, 256, 3).tolist()) # Fixed line
33
-
34
  def scan_qr_code(image):
 
 
 
 
 
 
35
  try:
36
- image_np = np.array(image)
37
- qr_detector = cv2.QRCodeDetector()
38
- data, _, _ = qr_detector.detectAndDecode(image_np)
39
- return data.strip() if data else None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  except Exception as e:
41
  logger.error(f"QR scan failed: {str(e)}")
42
  return None
@@ -83,8 +129,8 @@ def inference(img: Image.Image, confidence):
83
  ocr_text = " ".join(ocr_texts)
84
 
85
  labels = ["person name", "company name", "job title",
86
- "phone number", "email address", "address",
87
- "website"]
88
  entities = gliner_model.predict_entities(ocr_text, labels, threshold=confidence, flat_ner=True)
89
 
90
  results = {
@@ -162,11 +208,11 @@ def inference(img: Image.Image, confidence):
162
  results["Person Name"].append(text)
163
  break
164
 
165
- # QR Code
166
  if (qr_data := scan_qr_code(img)):
167
  results["QR Code"].append(qr_data)
168
 
169
- # Create CSV
170
  csv_data = {k: "; ".join(v) for k, v in results.items() if v}
171
  with tempfile.NamedTemporaryFile(suffix=".csv", delete=False, mode="w") as tmp_file:
172
  pd.DataFrame([csv_data]).to_csv(tmp_file, index=False)
@@ -195,4 +241,4 @@ if __name__ == '__main__':
195
  description=description,
196
  css=".gr-interface {max-width: 800px !important;}"
197
  )
198
- demo.launch()
 
11
  import io
12
  import re
13
  import traceback
14
+ import zxingcpp # Added zxingcpp for QR decoding
15
 
16
  # Configure logging
17
  logging.basicConfig(level=logging.INFO)
 
30
 
31
  # Get a random color (used for drawing bounding boxes, if needed)
32
  def get_random_color():
33
+ return tuple(np.random.randint(0, 256, 3).tolist())
34
+
35
  def scan_qr_code(image):
36
+ """
37
+ Attempts to scan a QR code from the given PIL image using zxingcpp.
38
+ The image is first saved to a temporary file to be read by zxingcpp.
39
+ If the direct decoding fails, the function tries a fallback
40
+ where the image is converted based on a default QR color (black) and tolerance.
41
+ """
42
  try:
43
+ # Save the PIL image to a temporary file
44
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
45
+ image.save(tmp, format="PNG")
46
+ tmp_path = tmp.name
47
+
48
+ # Convert the saved image to a CV2 image
49
+ img_cv = cv2.imread(tmp_path)
50
+ # First attempt: direct decoding with zxingcpp
51
+ try:
52
+ results = zxingcpp.read_barcodes(img_cv)
53
+ if results and results[0].text:
54
+ return results[0].text.strip()
55
+ except Exception as e:
56
+ logger.warning(f"Direct zxingcpp decoding failed: {e}")
57
+
58
+ # Fallback: Process image by converting specific QR colors with default parameters.
59
+ default_color = "#000000" # Default QR color assumed (black)
60
+ tolerance = 50 # Fixed tolerance value
61
+ qr_img = image.convert("RGB")
62
+ datas = list(qr_img.getdata())
63
+ newData = []
64
+ # Convert hex default color to an RGB tuple
65
+ h1 = default_color.strip("#")
66
+ rgb_tup = tuple(int(h1[i:i+2], 16) for i in (0, 2, 4))
67
+ for item in datas:
68
+ # Check if the pixel is within the tolerance of the default color
69
+ if (item[0] in range(rgb_tup[0]-tolerance, rgb_tup[0]+tolerance) and
70
+ item[1] in range(rgb_tup[1]-tolerance, rgb_tup[1]+tolerance) and
71
+ item[2] in range(rgb_tup[2]-tolerance, rgb_tup[2]+tolerance)):
72
+ newData.append((0, 0, 0))
73
+ else:
74
+ newData.append((255, 255, 255))
75
+ qr_img.putdata(newData)
76
+ fallback_path = tmp_path + "_converted.png"
77
+ qr_img.save(fallback_path)
78
+ img_cv = cv2.imread(fallback_path)
79
+ try:
80
+ results = zxingcpp.read_barcodes(img_cv)
81
+ if results and results[0].text:
82
+ return results[0].text.strip()
83
+ except Exception as e:
84
+ logger.error(f"Fallback decoding failed: {e}")
85
+ return None
86
  except Exception as e:
87
  logger.error(f"QR scan failed: {str(e)}")
88
  return None
 
129
  ocr_text = " ".join(ocr_texts)
130
 
131
  labels = ["person name", "company name", "job title",
132
+ "phone number", "email address", "address",
133
+ "website"]
134
  entities = gliner_model.predict_entities(ocr_text, labels, threshold=confidence, flat_ner=True)
135
 
136
  results = {
 
208
  results["Person Name"].append(text)
209
  break
210
 
211
+ # QR Code scanning using the new zxingcpp-based function
212
  if (qr_data := scan_qr_code(img)):
213
  results["QR Code"].append(qr_data)
214
 
215
+ # Create CSV file containing the results
216
  csv_data = {k: "; ".join(v) for k, v in results.items() if v}
217
  with tempfile.NamedTemporaryFile(suffix=".csv", delete=False, mode="w") as tmp_file:
218
  pd.DataFrame([csv_data]).to_csv(tmp_file, index=False)
 
241
  description=description,
242
  css=".gr-interface {max-width: 800px !important;}"
243
  )
244
+ demo.launch()