Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import requests
|
3 |
+
from PIL import Image
|
4 |
+
from io import BytesIO
|
5 |
+
import numpy as np
|
6 |
+
from landingai.common import decode_bitmap_rle
|
7 |
+
import cv2
|
8 |
+
import pydantic
|
9 |
+
|
10 |
+
ENDPOINT_ID = "ba678fa4-65d1-4b87-8c85-cebd15224783"
|
11 |
+
API_KEY = "land_sk_ikq7WEKGtaKI7pXIcKt2x7RoyYE6FBReqGOmKtEhjcmFbLbQsK"
|
12 |
+
API_URL = f"https://predict.app.landing.ai/inference/v1/predict?endpoint_id={ENDPOINT_ID}"
|
13 |
+
|
14 |
+
def predict_from_landinglens(image_path):
|
15 |
+
# Load and keep original image
|
16 |
+
original_img = Image.open(image_path).convert("RGB")
|
17 |
+
img_array = np.array(original_img)
|
18 |
+
|
19 |
+
# Get image dimensions
|
20 |
+
height, width = img_array.shape[:2]
|
21 |
+
total_pixels = height * width
|
22 |
+
|
23 |
+
# Prepare for API
|
24 |
+
buffered = BytesIO()
|
25 |
+
original_img.save(buffered, format="JPEG")
|
26 |
+
img_bytes = buffered.getvalue()
|
27 |
+
|
28 |
+
files = {"file": (image_path, img_bytes, "image/jpeg")}
|
29 |
+
headers = {"apikey": API_KEY}
|
30 |
+
|
31 |
+
try:
|
32 |
+
response = requests.post(API_URL, files=files, headers=headers)
|
33 |
+
if response.status_code == 503:
|
34 |
+
return "Service temporarily unavailable. Please try again later."
|
35 |
+
response.raise_for_status()
|
36 |
+
prediction = response.json()
|
37 |
+
|
38 |
+
if "predictions" not in prediction or not prediction.get("predictions"):
|
39 |
+
print("No 'predictions' key found or it's empty.")
|
40 |
+
return "Error: No 'predictions' found."
|
41 |
+
|
42 |
+
bitmaps = prediction["predictions"]["bitmaps"]
|
43 |
+
masked_images = []
|
44 |
+
coverage_info = []
|
45 |
+
|
46 |
+
for i, (bitmap_id, bitmap_data) in enumerate(bitmaps.items()):
|
47 |
+
try:
|
48 |
+
# Decode mask
|
49 |
+
mask = decode_bitmap_rle(bitmap_data["bitmap"])
|
50 |
+
if isinstance(mask, list):
|
51 |
+
mask = np.array(mask)
|
52 |
+
|
53 |
+
# Reshape mask to match image dimensions
|
54 |
+
mask = mask.reshape(prediction["predictions"]["imageHeight"],
|
55 |
+
prediction["predictions"]["imageWidth"])
|
56 |
+
|
57 |
+
# Calculate area coverage
|
58 |
+
mask_area = np.sum(mask > 0)
|
59 |
+
coverage_percentage = (mask_area / total_pixels) * 100
|
60 |
+
label_name = bitmap_data.get("label_name", f"Mask {i}")
|
61 |
+
coverage_info.append(f"{label_name}: {coverage_percentage:.2f}%")
|
62 |
+
|
63 |
+
# Create colored overlay
|
64 |
+
colored_mask = np.zeros_like(img_array)
|
65 |
+
colored_mask[mask > 0] = [255, 0, 0] # Red overlay for mask
|
66 |
+
|
67 |
+
# Combine original image with colored mask
|
68 |
+
alpha = 0.5 # Transparency of the overlay
|
69 |
+
combined = cv2.addWeighted(img_array, 1, colored_mask, alpha, 0)
|
70 |
+
|
71 |
+
# Convert to PIL Image
|
72 |
+
masked_image = Image.fromarray(combined)
|
73 |
+
masked_images.append(masked_image)
|
74 |
+
|
75 |
+
except Exception as e:
|
76 |
+
print(f"Error processing mask {i}: {e}")
|
77 |
+
continue
|
78 |
+
|
79 |
+
return masked_images, "\n".join(coverage_info)
|
80 |
+
|
81 |
+
except requests.exceptions.RequestException as e:
|
82 |
+
print(f"API Error: {e}")
|
83 |
+
return f"API Error: {e}"
|
84 |
+
|
85 |
+
iface = gr.Interface(
|
86 |
+
fn=predict_from_landinglens,
|
87 |
+
inputs=gr.Image(type="filepath"),
|
88 |
+
outputs=[
|
89 |
+
gr.Gallery(format="png"),
|
90 |
+
gr.Textbox(label="Area of each mask in the image")
|
91 |
+
],
|
92 |
+
title="Crosswalk detection model",
|
93 |
+
)
|
94 |
+
iface.launch()
|