soranz84 commited on
Commit
9d248f9
·
verified ·
1 Parent(s): fcc382c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -30
app.py CHANGED
@@ -16,9 +16,65 @@ import base64
16
 
17
  # model token
18
  model_key = os.getenv("hf_token")
19
- file_path = hf_hub_download("soranz84/grai2", "Model_047.h5",
20
  token=model_key)
21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  # Define the Mish activation function (essential for the model)
23
  class Mish(tf.keras.layers.Layer):
24
  def __init__(self, **kwargs):
@@ -39,7 +95,7 @@ def custom_loss(y_true, y_pred):
39
 
40
  # Initialize FastAPI app
41
  app = FastAPI(
42
- title="GRAI2 Soil Analysis API",
43
  description="API for soil particle size distribution analysis from images",
44
  version="1.0.0",
45
  docs_url="/docs",
@@ -104,35 +160,39 @@ def process_image(image: PILImage.Image) -> tuple:
104
  scale = 1
105
  supported_device = True
106
 
107
- # Device-specific scaling
108
- # Motorola Edge
109
- if width == 1800 and height == 4000:
110
- scale = 720/1800
111
- elif width == 4000 and height == 1800:
112
- scale = 720/1800
113
- # Samsung A52
114
- elif width == 6936 or width == 9248:
115
- scale = 1600/9248
116
- # iPhone 14
117
- elif width == 3024 or width == 4032:
118
- scale = 552/1673
119
- # iPhone 16
120
- elif width == 4284 or width == 5712:
121
- scale = 368/1562
122
- # Samsung A32 5G Aspect ratio 4:3
123
- elif width == 6000 or width == 8000:
124
- scale = 1334/7487
125
- # Samsung A32 5G Aspect ratio 16:9
126
- elif (width == 4000 and height == 2250) or (width == 2250 and height == 4000):
127
- scale = 1334/3744
128
- # Samsung Galaxy S23
129
- elif (width == 4000 and height == 3000) or (width == 3000 and height == 4000):
130
- scale = 1380/3746
131
- else:
132
- supported_device = False
133
- # Default scaling for unsupported devices
134
- scale = 1
135
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  # Calculate new dimensions
137
  new_width = int(width * scale)
138
  new_height = int(height * scale)
 
16
 
17
  # model token
18
  model_key = os.getenv("hf_token")
19
+ file_path = hf_hub_download("soranz84/grai3", "Model_3_076.h5",
20
  token=model_key)
21
 
22
+ # clean the camera string
23
+ def clean_exif_string(val):
24
+ if val is None:
25
+ return None
26
+
27
+ # Decode bytes using a few likely encodings
28
+ if isinstance(val, bytes):
29
+ for enc in ("utf-8", "utf-16", "utf-16le", "latin-1"):
30
+ try:
31
+ val = val.decode(enc)
32
+ break
33
+ except Exception:
34
+ pass
35
+ else:
36
+ val = val.decode("latin-1", errors="ignore")
37
+
38
+ # Remove null padding and non-printables
39
+ val = val.replace("\x00", "")
40
+ val = "".join(ch for ch in val if ch.isprintable())
41
+ return val.strip()
42
+
43
+ # find ppm and phone name
44
+ def find_ppm_and_phone_csv(
45
+ path: str,
46
+ camera: str,
47
+ w: int,
48
+ h: int,
49
+ phone: Optional[str] = None
50
+ ) -> Tuple[Optional[float], Optional[str]]:
51
+ cam = camera.strip().lower()
52
+ w, h = int(w), int(h)
53
+ phone_norm = phone.strip().lower() if phone else None
54
+
55
+ with open(path, newline="", encoding="utf-8") as f:
56
+ reader = csv.DictReader(f)
57
+ for row in reader:
58
+ cam_row = (row.get("camera", "")).strip().lower()
59
+ if cam_row != cam:
60
+ continue
61
+ if phone_norm:
62
+ if (row.get("phone", "")).strip().lower() != phone_norm:
63
+ continue
64
+ try:
65
+ rw = int(str(row.get("width", "")).strip())
66
+ rh = int(str(row.get("height", "")).strip())
67
+ ppm = float(str(row.get("ppm", "")).strip())
68
+ except ValueError:
69
+ continue
70
+
71
+ # Orientation-independent comparison
72
+ if (rw == w and rh == h) or (rw == h and rh == w):
73
+ phone_name = (row.get("phone", "")).strip() or None
74
+ return ppm, phone_name
75
+
76
+ return None, None
77
+
78
  # Define the Mish activation function (essential for the model)
79
  class Mish(tf.keras.layers.Layer):
80
  def __init__(self, **kwargs):
 
95
 
96
  # Initialize FastAPI app
97
  app = FastAPI(
98
+ title="grai3 Soil Analysis API",
99
  description="API for soil particle size distribution analysis from images",
100
  version="1.0.0",
101
  docs_url="/docs",
 
160
  scale = 1
161
  supported_device = True
162
 
163
+ # read metadata
164
+ width, height = image.size
165
+
166
+ camera = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
 
168
+ # Pillow >= 6 supports img.getexif(); older versions use _getexif()
169
+ raw_exif = None
170
+ try:
171
+ raw_exif = image.getexif()
172
+ except Exception:
173
+ raw_exif = getattr(image, "_getexif", lambda: None)()
174
+
175
+ if raw_exif:
176
+ exif = {}
177
+ for tag_id, value in raw_exif.items():
178
+ tag = ExifTags.TAGS.get(tag_id, tag_id)
179
+ exif[tag] = value
180
+ camera = exif.get("Model") # camera model (tag 272)
181
+ camera = clean_exif_string(camera)
182
+
183
+ # find ppm and phone name:
184
+ ppm, phone_name = (None, None)
185
+ if camera is not None:
186
+ ppm, phone_name = find_ppm_and_phone_csv("ppm.csv", camera, width, height)
187
+
188
+ # handle unkwnon phone camera
189
+ if ppm is None:
190
+ # Form to confirm guessed ppm
191
+ ppm = max(width,height)/294.087
192
+
193
+ # resize image to 4.6 PPM
194
+ scale = 4.6 / ppm
195
+
196
  # Calculate new dimensions
197
  new_width = int(width * scale)
198
  new_height = int(height * scale)