Download app/utils.py from CJR61/papi_cc: direct link, hf CLI and curl.
- Browser
- Download file 2.3 kB
-
https://huggingface.co/spaces/CJR61/papi_cc/resolve/main/app/utils.py
- Command line
-
hf download hf://spaces/CJR61/papi_cc/app/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/CJR61/papi_cc/resolve/main/app/utils.py
2.3 kB
| import cv2 | |
| import numpy as np | |
| import os | |
| import csv | |
| import uuid | |
| from datetime import datetime | |
| ALLOWED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".tif"} | |
| def save_uploaded_file(save_dir, file): | |
| # Validate file extension | |
| _, ext = os.path.splitext(file.filename or "") | |
| if ext.lower() not in ALLOWED_EXTENSIONS: | |
| raise ValueError(f"Unsupported file type '{ext}'. Allowed: {ALLOWED_EXTENSIONS}") | |
| # Ensure upload directory exists | |
| os.makedirs(save_dir, exist_ok=True) | |
| # Generate unique ID (date prefix + uuid4) to avoid race condition | |
| image_id = datetime.now().strftime("%Y%m%d_%H%M%S") + "_" + uuid.uuid4().hex[:8] | |
| saved_path = os.path.join(save_dir, f"{image_id}.jpg") | |
| # Save file | |
| with open(saved_path, "wb") as f: | |
| f.write(file.file.read()) | |
| return saved_path, image_id | |
| def is_valid_image(file_path): | |
| try: | |
| image = cv2.imread(file_path) | |
| if image is None: | |
| return False | |
| return True | |
| except Exception: | |
| return False | |
| def preprocess_image(image_path): | |
| # Read image — Resize(256) + CenterCrop(224) to match training val_transform | |
| image = cv2.imread(image_path) | |
| image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) | |
| h, w = image.shape[:2] | |
| if h < w: | |
| new_h, new_w = 256, int(w * 256 / h) | |
| else: | |
| new_h, new_w = int(h * 256 / w), 256 | |
| image = cv2.resize(image, (new_w, new_h)) | |
| y0 = (new_h - 224) // 2 | |
| x0 = (new_w - 224) // 2 | |
| image = image[y0:y0+224, x0:x0+224] | |
| image = image / 255.0 | |
| mean = np.array([0.485, 0.456, 0.406]) | |
| std = np.array([0.229, 0.224, 0.225]) | |
| image = (image - mean) / std | |
| image = np.transpose(image, (2, 0, 1)) # HWC -> CHW | |
| input_tensor = np.expand_dims(image, axis=0).astype(np.float32) | |
| return input_tensor | |
| def append_to_csv(csv_path, image_id, prediction, probability, similarity): | |
| # Ensure CSV file exists | |
| os.makedirs(os.path.dirname(csv_path), exist_ok=True) | |
| file_exists = os.path.isfile(csv_path) | |
| with open(csv_path, mode="a", newline="") as f: | |
| writer = csv.writer(f) | |
| if not file_exists: | |
| writer.writerow(["ID", "Prediction", "Probability", "Similarity"]) | |
| writer.writerow([image_id, prediction, probability, round(float(similarity), 3)]) | |