Kamlesh21 commited on
Commit
b0acf7c
·
verified ·
1 Parent(s): debf222

Deploy Preprocessing Lab

Browse files
Files changed (42) hide show
  1. README.md +31 -6
  2. app.py +40 -162
  3. data/coco/000000000049.jpg +0 -0
  4. data/coco/000000000074.jpg +0 -0
  5. data/coco/000000000136.jpg +0 -0
  6. data/coco/000000000143.jpg +0 -0
  7. data/coco/000000000597.jpg +0 -0
  8. data/coco/000000000599.jpg +0 -0
  9. data/manifest.json +150 -0
  10. data/pets/beagle.jpg +0 -0
  11. data/pets/boxer.jpg +0 -0
  12. data/pets/chihuahua.jpg +0 -0
  13. data/pets/egyptian_mau.jpg +0 -0
  14. data/pets/persian.jpg +0 -0
  15. data/pets/pug.jpg +0 -0
  16. data/pets/saint_bernard.jpg +0 -0
  17. data/pets/samoyed.jpg +0 -0
  18. image_lab.ipynb +798 -0
  19. packages.txt +2 -0
  20. requirements.txt +7 -2
  21. scripts/fetch_data.py +118 -0
  22. scripts/fetch_models.py +26 -0
  23. server.py +436 -0
  24. static/assets/bricolage-grotesque-latin-ext-wght-normal-CcLUaPy7.woff2 +0 -0
  25. static/assets/bricolage-grotesque-latin-wght-normal-DLoelf7F.woff2 +0 -0
  26. static/assets/bricolage-grotesque-vietnamese-wght-normal-BUzh504Q.woff2 +0 -0
  27. static/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  28. static/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  29. static/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  30. static/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  31. static/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
  32. static/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
  33. static/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
  34. static/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
  35. static/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
  36. static/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
  37. static/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  38. static/assets/index-3TAydZ6P.js +0 -0
  39. static/assets/index-BRWcS88i.css +1 -0
  40. static/index.html +14 -0
  41. weights/torch/hub/checkpoints/resnet50-0676ba61.pth +3 -0
  42. weights/yolo11s-seg.pt +3 -0
README.md CHANGED
@@ -1,12 +1,37 @@
1
  ---
2
- title: AIJOKER
3
- emoji: 📚
4
  colorFrom: blue
5
- colorTo: yellow
6
  sdk: gradio
7
- sdk_version: 5.20.0
8
  app_file: app.py
9
- pinned: false
 
 
 
 
 
 
 
 
 
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Preprocessing Lab
3
+ emoji: 🔬
4
  colorFrom: blue
5
+ colorTo: pink
6
  sdk: gradio
7
+ sdk_version: 6.28.0
8
  app_file: app.py
9
+ python_version: "3.12"
10
+ short_description: See how preprocessing changes what a vision model sees
11
+ startup_duration_timeout: 30m
12
+ tags:
13
+ - education
14
+ - image-preprocessing
15
+ - image-classification
16
+ - instance-segmentation
17
+ - resnet
18
+ - yolo
19
  ---
20
 
21
+ # Preprocessing Lab
22
+
23
+ A teaching app about one idea: **a model only works on the input it was trained on.** One photo goes through
24
+ preprocessing steps into ResNet50 (classify a pet) or YOLO11s-seg (find, outline and count objects). Every step shows
25
+ its image, the exact Python code that ran, and why it exists.
26
+
27
+ - **Preparation** steps are on: BGR→RGB, resize, crop or letterbox, normalize, channels first. Skip one and watch the
28
+ model break (skip Normalize: the boxer becomes a "spotlight").
29
+ - **Break it** switches do what the real world does to photos: rotate, dark, blur, noise, low resolution.
30
+ - **Fix it** switches are classic enhancement and restoration: gamma, histogram equalization, CLAHE, denoising,
31
+ median filter, sharpening, straightening. Some bring the answer back; some can't (lost detail is gone for good).
32
+
33
+ Keys: `←` `→` walk the pipeline, `1`–`6` break-it switches, `H` histogram, `E` explain & code.
34
+
35
+ Source, notebook and tests: https://github.com/JustKamlesH21/image-preprocessing-demo
36
+ Images: Oxford-IIIT Pet (CC BY-SA 4.0) and COCO 2017 (CC BY 4.0 annotations, Flickr image licenses).
37
+ Models: ResNet50 (torchvision, BSD-3-Clause), YOLO11s-seg (Ultralytics, AGPL-3.0).
app.py CHANGED
@@ -1,176 +1,54 @@
1
- import os
2
- import gradio as gr
3
- import google.generativeai as genai
4
- import random
5
-
6
- # ✅ Securely get API key from environment variables
7
- gemini_api_key = os.environ.get("GEMINI_API_KEY")
8
- if not gemini_api_key:
9
- raise ValueError("""
10
- ⚠️ ERROR: Gemini API Key is missing!
11
- Set your API key in environment variables using:
12
- export GEMINI_API_KEY='your-api-key-here'
13
- """)
14
-
15
- # ✅ Configure Gemini API
16
- genai.configure(api_key=gemini_api_key)
17
-
18
- def get_joke(language):
19
- """Get a joke in the selected language (English or Hinglish)"""
20
- try:
21
- model = genai.GenerativeModel("models/gemini-2.0-flash-lite")
22
 
23
- # ✅ Random funny words for more variety
24
- random_word = random.choice([
25
- "banana", "robot", "pirate", "spaceship", "wizard", "penguin",
26
- "vampire", "dinosaur", "detective", "ninja", "zombie", "alien",
27
- "astronaut", "time traveler", "cowboy", "unicorn", "octopus",
28
- "squirrel", "chicken", "ghost", "superhero", "scientist",
29
- "teacher", "doctor", "chef", "dog", "cat", "hamster", "elephant",
30
- "monkey", "koala", "turtle", "cactus", "caveman", "jellyfish",
31
- "kangaroo", "mermaid", "gnome", "fairy", "dragon", "owl",
32
- "skeleton", "t-rex", "werewolf", "bigfoot", "genie", "goldfish",
33
- "duck", "giraffe", "parrot", "sloth", "teddy bear", "panda",
34
- "penguin", "robot", "unicorn", "vampire", "zombie", "alien"
35
- ])
36
-
37
- # ✅ Language-based prompt selection
38
- if language == "English":
39
- prompt = f"Tell me a funny, unique joke about {random_word}. Keep it in simple, clear English."
40
- else: # Hinglish (Mix of Hindi & English)
41
- prompt = f"Ek funny joke sunao {random_word} ke baare mein, jo thoda Hindi aur thoda English mila ho. Thoda desi touch ho!"
42
 
43
- response = model.generate_content(
44
- prompt,
45
- generation_config={
46
- "temperature": 1.2, # More creativity
47
- "top_p": 0.9, # Diverse responses
48
- "max_output_tokens": 100 # Limit response length
49
- }
50
- )
51
-
52
- return response.text if response and hasattr(response, 'text') else "⚠️ No joke found."
53
-
54
- except Exception as e:
55
- return f"⚠️ Error generating joke: {str(e)}"
56
 
 
57
 
58
- def rate_joke(feedback):
59
- """Handle user feedback"""
60
- return f"Thanks for your feedback! You rated: {feedback}"
61
-
62
- # ✅ Improved Gradio UI with a dark striped background
63
- with gr.Blocks(css="""
64
- body {
65
- background-color: #000000; /* Changed to Black */
66
- }
67
- h1, h3 {
68
- font-family: Arial, sans-serif;
69
- text-align: center;
70
- color: white;
71
- }
72
- #joke-box {
73
- background-color: #D3D3D3;
74
- color: white;
75
- border-radius: 10px;
76
- font-size: 32px; /* Increased size */
77
- font-weight: bold; /* Bold text */
78
- font-family: 'Comic Sans MS', cursive; /* Fun font */
79
- padding: 20px;
80
- }
81
- #joke-button {
82
- background: #8A2BE2; /* Purple */
83
- color: white;
84
- font-weight: bold;
85
- font-size: 1.2em;
86
- border-radius: 10px;
87
- padding: 10px;
88
- }
89
- #feedback-buttons {
90
- display: flex;
91
- justify-content: center;
92
- gap: 10px;
93
- }
94
- .funny-button {
95
- background-color: #00C853; /* Bright Green */
96
- color: white;
97
- font-weight: bold;
98
- font-size: 1.2em;
99
- border-radius: 10px;
100
- padding: 10px;
101
- }
102
- .not-funny-button {
103
- background-color: #D32F2F; /* Deep Red */
104
- color: white;
105
- font-weight: bold;
106
- font-size: 1.2em;
107
- border-radius: 10px;
108
- padding: 10px;
109
- }
110
- """) as app:
111
-
112
- gr.Markdown("""
113
- <div style="text-align: center; font-family: Arial, sans-serif;">
114
- <h1 style="font-size: 2.8em; font-weight: bold;">
115
- 🤣 AI'S GOT LATENT 🤣
116
- </h1>
117
- <h3 style="font-size: 2em;">
118
- Don't worry only family friendly jokes!😉
119
- </h3>
120
- </div>
121
- """)
122
-
123
- with gr.Column(elem_id="main-container", scale=1, min_width=1000):
124
-
125
- # ✅ Language selection dropdown
126
- language_dropdown = gr.Dropdown(
127
- choices=["English", "Hinglish"],
128
- value="English",
129
- label="Select Joke Language"
130
- )
131
 
132
- # ✅ Output box
133
- joke_output = gr.Textbox(
134
- placeholder="Your joke will appear here...",
135
- interactive=False,
136
- lines=5,
137
- show_label=False,
138
- elem_id="joke-box"
139
- )
140
 
141
- # ✅ Joke button (Purple)
142
- joke_button = gr.Button(
143
- "🎲 Generate a Joke", variant="primary",
144
- elem_id="joke-button"
145
- )
 
146
 
147
- gr.Markdown("""
148
- <div style="text-align: center; font-size: 2em; margin-top: 20px; color: white;">
149
- <strong>Did you like this joke?</strong>
150
- </div>
151
- """)
152
 
153
- with gr.Row(elem_id="feedback-buttons", equal_height=True):
154
- thumbs_up = gr.Button("👍 Funny!", elem_classes=["funny-button"]) # Green
155
- thumbs_down = gr.Button("👎 Not Funny", elem_classes=["not-funny-button"]) # Red
 
 
156
 
157
- feedback_output = gr.Textbox(
158
- label="Feedback",
159
- interactive=False,
160
- visible=True,
161
- elem_id="feedback-box"
162
- )
163
 
164
- # ✅ Button click now includes language selection
165
- joke_button.click(get_joke, inputs=language_dropdown, outputs=joke_output)
166
- thumbs_up.click(lambda: rate_joke("👍 Funny!"), outputs=feedback_output)
167
- thumbs_down.click(lambda: rate_joke("👎 Not Funny"), outputs=feedback_output)
168
 
 
169
 
 
170
 
171
- # ✅ Secure launch configuration
172
  if __name__ == "__main__":
173
- app.launch(
174
- share=True,
175
- debug=False
176
- )
 
1
+ """Hugging Face Space entry point: the whole Preprocessing Lab (app + API) at one URL.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ Free accounts can only run Python Spaces on ZeroGPU hardware, which needs the Gradio SDK and at least one
4
+ @spaces.GPU function. The lab itself runs on CPU (both models are fast enough), so the one GPU function below is a
5
+ no-op that is never called: visitors never spend any GPU quota.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ deploy_space.py uploads this file next to backend/server.py, the notebook, the data, the weights, and the built
8
+ frontend (static/), so the Space runs exactly the code in this repository.
9
+ """
 
 
 
 
 
 
 
 
 
 
10
 
11
+ import spaces # must be imported before torch
12
 
13
+ import os
14
+ import subprocess
15
+ import sys
16
+ import threading
17
+ from pathlib import Path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
+ HERE = Path(__file__).resolve().parent
20
+ os.environ.setdefault("TORCH_HOME", str(HERE / "weights" / "torch"))
 
 
 
 
 
 
21
 
22
+ # Images and weights are uploaded with the Space; download them only if they are missing.
23
+ if not (HERE / "data" / "manifest.json").exists():
24
+ subprocess.run([sys.executable, "scripts/fetch_data.py"], cwd=HERE, check=True)
25
+ if not (HERE / "weights" / "yolo11s-seg.pt").exists():
26
+ subprocess.run([sys.executable, "scripts/fetch_models.py"], cwd=HERE, check=True)
27
+ os.environ["YOLO_OFFLINE"] = "1"
28
 
29
+ import server # noqa: E402 (runs image_lab.ipynb)
30
+ from fastapi.middleware.cors import CORSMiddleware # noqa: E402
31
+ from fastapi.responses import FileResponse # noqa: E402
32
+ from gradio import Server # noqa: E402
33
+ from starlette.staticfiles import StaticFiles # noqa: E402
34
 
35
+ app = Server(title="Preprocessing Lab")
36
+ app.add_middleware(CORSMiddleware, allow_origins=[o.strip() for o in os.environ.get("ALLOWED_ORIGINS", "*").split(",")],
37
+ allow_methods=["GET", "POST"], allow_headers=["*"])
38
+ app.include_router(server.app.router) # every /api/... route from server.py
39
+ app.add_exception_handler(Exception, server.crash)
40
 
41
+ STATIC = HERE / "static"
42
+ if STATIC.exists(): # the built frontend: the page students open
43
+ app.mount("/assets", StaticFiles(directory=STATIC / "assets"), name="assets")
 
 
 
44
 
45
+ @app.get("/", include_in_schema=False)
46
+ def index():
47
+ return FileResponse(STATIC / "index.html")
 
48
 
49
+ threading.Thread(target=server.warm_up, daemon=True).start()
50
 
51
+ spaces.GPU(lambda: None) # ZeroGPU needs one GPU function; the lab runs on CPU and never calls it
52
 
 
53
  if __name__ == "__main__":
54
+ app.launch(server_name="0.0.0.0", server_port=7860, show_error=True)
 
 
 
data/coco/000000000049.jpg ADDED
data/coco/000000000074.jpg ADDED
data/coco/000000000136.jpg ADDED
data/coco/000000000143.jpg ADDED
data/coco/000000000597.jpg ADDED
data/coco/000000000599.jpg ADDED
data/manifest.json ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "images": [
3
+ {
4
+ "id": "pet-pug",
5
+ "use_case": "classify",
6
+ "file": "pets/pug.jpg",
7
+ "title": "Pug",
8
+ "label": "pug",
9
+ "license": "CC BY-SA 4.0",
10
+ "source": "Oxford-IIIT Pet Dataset (Parkhi et al., 2012), test split, via huggingface.co/datasets/timm/oxford-iiit-pet"
11
+ },
12
+ {
13
+ "id": "pet-samoyed",
14
+ "use_case": "classify",
15
+ "file": "pets/samoyed.jpg",
16
+ "title": "Samoyed",
17
+ "label": "Samoyed",
18
+ "license": "CC BY-SA 4.0",
19
+ "source": "Oxford-IIIT Pet Dataset (Parkhi et al., 2012), test split, via huggingface.co/datasets/timm/oxford-iiit-pet"
20
+ },
21
+ {
22
+ "id": "pet-beagle",
23
+ "use_case": "classify",
24
+ "file": "pets/beagle.jpg",
25
+ "title": "Beagle",
26
+ "label": "beagle",
27
+ "license": "CC BY-SA 4.0",
28
+ "source": "Oxford-IIIT Pet Dataset (Parkhi et al., 2012), test split, via huggingface.co/datasets/timm/oxford-iiit-pet"
29
+ },
30
+ {
31
+ "id": "pet-saint_bernard",
32
+ "use_case": "classify",
33
+ "file": "pets/saint_bernard.jpg",
34
+ "title": "Saint Bernard",
35
+ "label": "Saint Bernard",
36
+ "license": "CC BY-SA 4.0",
37
+ "source": "Oxford-IIIT Pet Dataset (Parkhi et al., 2012), test split, via huggingface.co/datasets/timm/oxford-iiit-pet"
38
+ },
39
+ {
40
+ "id": "pet-boxer",
41
+ "use_case": "classify",
42
+ "file": "pets/boxer.jpg",
43
+ "title": "Boxer",
44
+ "label": "boxer",
45
+ "license": "CC BY-SA 4.0",
46
+ "source": "Oxford-IIIT Pet Dataset (Parkhi et al., 2012), test split, via huggingface.co/datasets/timm/oxford-iiit-pet"
47
+ },
48
+ {
49
+ "id": "pet-chihuahua",
50
+ "use_case": "classify",
51
+ "file": "pets/chihuahua.jpg",
52
+ "title": "Chihuahua",
53
+ "label": "Chihuahua",
54
+ "license": "CC BY-SA 4.0",
55
+ "source": "Oxford-IIIT Pet Dataset (Parkhi et al., 2012), test split, via huggingface.co/datasets/timm/oxford-iiit-pet"
56
+ },
57
+ {
58
+ "id": "pet-persian",
59
+ "use_case": "classify",
60
+ "file": "pets/persian.jpg",
61
+ "title": "Persian",
62
+ "label": "Persian cat",
63
+ "license": "CC BY-SA 4.0",
64
+ "source": "Oxford-IIIT Pet Dataset (Parkhi et al., 2012), test split, via huggingface.co/datasets/timm/oxford-iiit-pet"
65
+ },
66
+ {
67
+ "id": "pet-egyptian_mau",
68
+ "use_case": "classify",
69
+ "file": "pets/egyptian_mau.jpg",
70
+ "title": "Egyptian Mau",
71
+ "label": "Egyptian cat",
72
+ "license": "CC BY-SA 4.0",
73
+ "source": "Oxford-IIIT Pet Dataset (Parkhi et al., 2012), test split, via huggingface.co/datasets/timm/oxford-iiit-pet"
74
+ },
75
+ {
76
+ "id": "coco-000000000049",
77
+ "use_case": "segment",
78
+ "file": "coco/000000000049.jpg",
79
+ "title": "6 person, 2 horse, 1 potted plant",
80
+ "gt_counts": {
81
+ "horse": 2,
82
+ "person": 6,
83
+ "potted plant": 1
84
+ },
85
+ "license": "COCO annotations CC BY 4.0; images under their Flickr licenses",
86
+ "source": "COCO 2017 via Ultralytics coco128-seg (train2017 subset, so the model has seen these images)"
87
+ },
88
+ {
89
+ "id": "coco-000000000074",
90
+ "use_case": "segment",
91
+ "file": "coco/000000000074.jpg",
92
+ "title": "6 person, 1 dog, 1 bicycle",
93
+ "gt_counts": {
94
+ "dog": 1,
95
+ "bicycle": 1,
96
+ "person": 6
97
+ },
98
+ "license": "COCO annotations CC BY 4.0; images under their Flickr licenses",
99
+ "source": "COCO 2017 via Ultralytics coco128-seg (train2017 subset, so the model has seen these images)"
100
+ },
101
+ {
102
+ "id": "coco-000000000143",
103
+ "use_case": "segment",
104
+ "file": "coco/000000000143.jpg",
105
+ "title": "8 bird",
106
+ "gt_counts": {
107
+ "bird": 8
108
+ },
109
+ "license": "COCO annotations CC BY 4.0; images under their Flickr licenses",
110
+ "source": "COCO 2017 via Ultralytics coco128-seg (train2017 subset, so the model has seen these images)"
111
+ },
112
+ {
113
+ "id": "coco-000000000597",
114
+ "use_case": "segment",
115
+ "file": "coco/000000000597.jpg",
116
+ "title": "7 elephant",
117
+ "gt_counts": {
118
+ "elephant": 7
119
+ },
120
+ "license": "COCO annotations CC BY 4.0; images under their Flickr licenses",
121
+ "source": "COCO 2017 via Ultralytics coco128-seg (train2017 subset, so the model has seen these images)"
122
+ },
123
+ {
124
+ "id": "coco-000000000136",
125
+ "use_case": "segment",
126
+ "file": "coco/000000000136.jpg",
127
+ "title": "2 person, 2 giraffe",
128
+ "gt_counts": {
129
+ "person": 2,
130
+ "giraffe": 2
131
+ },
132
+ "license": "COCO annotations CC BY 4.0; images under their Flickr licenses",
133
+ "source": "COCO 2017 via Ultralytics coco128-seg (train2017 subset, so the model has seen these images)"
134
+ },
135
+ {
136
+ "id": "coco-000000000599",
137
+ "use_case": "segment",
138
+ "file": "coco/000000000599.jpg",
139
+ "title": "2 remote, 1 potted plant, 1 cat, 1 couch",
140
+ "gt_counts": {
141
+ "potted plant": 1,
142
+ "cat": 1,
143
+ "couch": 1,
144
+ "remote": 2
145
+ },
146
+ "license": "COCO annotations CC BY 4.0; images under their Flickr licenses",
147
+ "source": "COCO 2017 via Ultralytics coco128-seg (train2017 subset, so the model has seen these images)"
148
+ }
149
+ ]
150
+ }
data/pets/beagle.jpg ADDED
data/pets/boxer.jpg ADDED
data/pets/chihuahua.jpg ADDED
data/pets/egyptian_mau.jpg ADDED
data/pets/persian.jpg ADDED
data/pets/pug.jpg ADDED
data/pets/saint_bernard.jpg ADDED
data/pets/samoyed.jpg ADDED
image_lab.ipynb ADDED
@@ -0,0 +1,798 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "5642696a",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Image Preprocessing Lab\n",
9
+ "\n",
10
+ "Everything the demo does lives in this notebook: every preprocessing step, the two preset lines, and the two models.\n",
11
+ "It is plain Python: functions and dictionaries, no classes.\n",
12
+ "\n",
13
+ "The lab tells two stories about the same idea, **a model only works on the input it was trained on**:\n",
14
+ "\n",
15
+ "1. **Classify** a pet photo with ResNet50.\n",
16
+ "2. **Segment and count** objects with YOLO11s-seg.\n",
17
+ "\n",
18
+ "Each line has three kinds of steps:\n",
19
+ "\n",
20
+ "- **Preparation** steps turn a photo into exactly what the model expects. They are on.\n",
21
+ "- **Break it** steps copy what the real world does to photos: tilted cameras, dark rooms, blur, sensor noise,\n",
22
+ " low resolution. They are off. Switch one on and watch the model's answer change.\n",
23
+ "- **Fix it** steps are classic enhancement and restoration: straighten, brighten, equalize, denoise, sharpen.\n",
24
+ " They are off too. Break the photo, switch on a fix, and see how much of the answer comes back (often only part).\n",
25
+ "\n",
26
+ "**The web app loads this same notebook.** `server.py` runs every cell *except* the ones tagged `demo` (at the end),\n",
27
+ "so a function you change here changes what the app runs and shows.\n",
28
+ "\n",
29
+ "Conventions: images are NumPy arrays. Color images are `(height, width, 3)` in **RGB** order and `uint8` (0..255),\n",
30
+ "except straight after `cv2.imread`, which gives **BGR**."
31
+ ]
32
+ },
33
+ {
34
+ "cell_type": "code",
35
+ "execution_count": null,
36
+ "id": "8d2c5fe2",
37
+ "metadata": {},
38
+ "outputs": [],
39
+ "source": [
40
+ "import cv2\n",
41
+ "import numpy as np\n",
42
+ "\n",
43
+ "# Every step the app can use: step id -> dict(name, kind, fn, params, summary, explain).\n",
44
+ "STEPS = {}\n",
45
+ "\n",
46
+ "KINDS = {\n",
47
+ " \"prep\": \"Preparation\", # what the model needs\n",
48
+ " \"break\": \"Break it\", # what the real world does to photos\n",
49
+ " \"fix\": \"Fix it\", # enhancement and restoration that try to undo the damage\n",
50
+ "}\n",
51
+ "\n",
52
+ "\n",
53
+ "def slider(name, default, lo, hi, step=1, label=None, odd=False):\n",
54
+ " is_int = all(isinstance(v, int) for v in (default, lo, hi, step))\n",
55
+ " return dict(name=name, type=\"int\" if is_int else \"float\", default=default,\n",
56
+ " min=lo, max=hi, step=step, label=label or name, odd=odd)\n",
57
+ "\n",
58
+ "\n",
59
+ "def add_step(fn, name, kind, summary, explain, params=(), short=None, helps=()):\n",
60
+ " # short: a label that fits on a step pill (defaults to name).\n",
61
+ " # helps: for a fix step, the break-it steps it counteracts.\n",
62
+ " STEPS[fn.__name__] = dict(id=fn.__name__, name=name, short=short or name, kind=kind, fn=fn,\n",
63
+ " params=list(params), summary=summary, explain=explain, helps=list(helps))"
64
+ ]
65
+ },
66
+ {
67
+ "cell_type": "markdown",
68
+ "id": "0c869e68",
69
+ "metadata": {},
70
+ "source": [
71
+ "## Load an image"
72
+ ]
73
+ },
74
+ {
75
+ "cell_type": "code",
76
+ "execution_count": null,
77
+ "id": "c24212e0",
78
+ "metadata": {},
79
+ "outputs": [],
80
+ "source": [
81
+ "def load_image(path, max_side=640):\n",
82
+ " img = cv2.imread(str(path)) # OpenCV loads 3 channels in B, G, R order, dtype uint8\n",
83
+ " h, w = img.shape[:2]\n",
84
+ " s = max_side / max(h, w)\n",
85
+ " if s < 1: # keep the demo fast: shrink big photos, never enlarge small ones\n",
86
+ " img = cv2.resize(img, (round(w * s), round(h * s)), interpolation=cv2.INTER_AREA)\n",
87
+ " return img"
88
+ ]
89
+ },
90
+ {
91
+ "cell_type": "markdown",
92
+ "id": "bae4c60e",
93
+ "metadata": {},
94
+ "source": [
95
+ "## Preparation: what the model needs\n",
96
+ "\n",
97
+ "A trained network expects one exact kind of input: a fixed color order, a fixed size, a fixed value range and a\n",
98
+ "fixed memory layout. These steps get a photo there."
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": null,
104
+ "id": "77fd08a3",
105
+ "metadata": {},
106
+ "outputs": [],
107
+ "source": [
108
+ "def bgr_to_rgb(img):\n",
109
+ " return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n",
110
+ "\n",
111
+ "add_step(bgr_to_rgb, \"BGR to RGB\", \"prep\", short=\"BGR → RGB\",\n",
112
+ " summary=\"Swap OpenCV's blue-first channel order to red-first.\",\n",
113
+ " explain=\"cv2.imread returns pixels as Blue, Green, Red. The models were trained on Red, Green, Blue. \"\n",
114
+ " \"Switch this off and every red turns blue: the model still answers, just less sure, \"\n",
115
+ " \"and nothing crashes. A classic silent bug.\")"
116
+ ]
117
+ },
118
+ {
119
+ "cell_type": "code",
120
+ "execution_count": null,
121
+ "id": "d0313d1b",
122
+ "metadata": {},
123
+ "outputs": [],
124
+ "source": [
125
+ "def resize_shorter(img, size=256):\n",
126
+ " h, w = img.shape[:2]\n",
127
+ " s = size / min(h, w)\n",
128
+ " return cv2.resize(img, (round(w * s), round(h * s)), interpolation=cv2.INTER_AREA)\n",
129
+ "\n",
130
+ "add_step(resize_shorter, \"Resize\", \"prep\",\n",
131
+ " summary=\"Scale the shorter side to 256 pixels, keeping the shape.\",\n",
132
+ " explain=\"ResNet50 was trained on 224 by 224 images. First the shorter side is scaled to 256 so nothing gets \"\n",
133
+ " \"squashed, then the next step cuts out the middle.\",\n",
134
+ " params=[slider(\"size\", 256, 128, 512, 8)])"
135
+ ]
136
+ },
137
+ {
138
+ "cell_type": "code",
139
+ "execution_count": null,
140
+ "id": "dba55c8a",
141
+ "metadata": {},
142
+ "outputs": [],
143
+ "source": [
144
+ "def center_crop(img, size=224):\n",
145
+ " h, w = img.shape[:2]\n",
146
+ " top, left = max(0, (h - size) // 2), max(0, (w - size) // 2)\n",
147
+ " return img[top:top + size, left:left + size]\n",
148
+ "\n",
149
+ "add_step(center_crop, \"Center crop\", \"prep\", short=\"Crop\",\n",
150
+ " summary=\"Cut a 224 by 224 square from the middle.\",\n",
151
+ " explain=\"Cropping is plain array slicing: rows first, then columns. Anything near the border is thrown \"\n",
152
+ " \"away, so an animal that is off to the side can be cut out here.\",\n",
153
+ " params=[slider(\"size\", 224, 64, 512, 8)])"
154
+ ]
155
+ },
156
+ {
157
+ "cell_type": "code",
158
+ "execution_count": null,
159
+ "id": "e070fbbc",
160
+ "metadata": {},
161
+ "outputs": [],
162
+ "source": [
163
+ "def letterbox(img, size=640):\n",
164
+ " h, w = img.shape[:2]\n",
165
+ " s = size / max(h, w)\n",
166
+ " nh, nw = round(h * s), round(w * s)\n",
167
+ " resized = cv2.resize(img, (nw, nh), interpolation=cv2.INTER_LINEAR)\n",
168
+ " top, left = (size - nh) // 2, (size - nw) // 2\n",
169
+ " return cv2.copyMakeBorder(resized, top, size - nh - top, left, size - nw - left,\n",
170
+ " cv2.BORDER_CONSTANT, value=(114, 114, 114))\n",
171
+ "\n",
172
+ "add_step(letterbox, \"Letterbox\", \"prep\",\n",
173
+ " summary=\"Fit the photo into a 640 by 640 square, padding with grey.\",\n",
174
+ " explain=\"YOLO takes a square image but must not stretch objects. Letterboxing scales the long side to 640, \"\n",
175
+ " \"then fills the rest with grey (114). Stretching instead would turn round objects into ovals.\",\n",
176
+ " params=[slider(\"size\", 640, 320, 1024, 32)])"
177
+ ]
178
+ },
179
+ {
180
+ "cell_type": "code",
181
+ "execution_count": null,
182
+ "id": "aa24a1f5",
183
+ "metadata": {},
184
+ "outputs": [],
185
+ "source": [
186
+ "def normalize(img):\n",
187
+ " mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)\n",
188
+ " std = np.array([0.229, 0.224, 0.225], dtype=np.float32)\n",
189
+ " return (img.astype(np.float32) / 255.0 - mean) / std\n",
190
+ "\n",
191
+ "add_step(normalize, \"Normalize\", \"prep\",\n",
192
+ " summary=\"Turn 0..255 pixel values into small numbers around 0.\",\n",
193
+ " explain=\"Divide by 255 to get 0..1, then subtract the ImageNet mean and divide by its standard deviation, \"\n",
194
+ " \"per channel. The model was trained on values roughly between -2 and 2. Switch this off and it \"\n",
195
+ " \"receives values up to 255: its answer becomes nonsense.\")"
196
+ ]
197
+ },
198
+ {
199
+ "cell_type": "code",
200
+ "execution_count": null,
201
+ "id": "6ec55aa2",
202
+ "metadata": {},
203
+ "outputs": [],
204
+ "source": [
205
+ "def to_chw(img):\n",
206
+ " return np.ascontiguousarray(img.transpose(2, 0, 1))\n",
207
+ "\n",
208
+ "add_step(to_chw, \"Channels first\", \"prep\", short=\"HWC → CHW\",\n",
209
+ " summary=\"Reorder the array from height, width, channels to channels, height, width.\",\n",
210
+ " explain=\"Images are stored as (224, 224, 3). PyTorch wants (3, 224, 224). No pixel changes, only the order \"\n",
211
+ " \"of the axes in memory.\")"
212
+ ]
213
+ },
214
+ {
215
+ "cell_type": "markdown",
216
+ "id": "51221b67",
217
+ "metadata": {},
218
+ "source": [
219
+ "## Break it: what the real world does to photos\n",
220
+ "\n",
221
+ "Each of these copies a problem real photos have. They are switched off in the presets."
222
+ ]
223
+ },
224
+ {
225
+ "cell_type": "code",
226
+ "execution_count": null,
227
+ "id": "c1aa6046",
228
+ "metadata": {},
229
+ "outputs": [],
230
+ "source": [
231
+ "def rotate(img, angle=45):\n",
232
+ " h, w = img.shape[:2]\n",
233
+ " M = cv2.getRotationMatrix2D((w / 2, h / 2), angle, 1.0)\n",
234
+ " return cv2.warpAffine(img, M, (w, h))\n",
235
+ "\n",
236
+ "add_step(rotate, \"Rotate\", \"break\",\n",
237
+ " summary=\"Tilt the photo, like a phone held at an angle.\",\n",
238
+ " explain=\"Most training photos are upright, so the model has rarely seen a tilted dog. The corners that \"\n",
239
+ " \"rotate out of frame are filled with black, which the model can mistake for content.\",\n",
240
+ " params=[slider(\"angle\", 45, -180, 180, 5, \"angle (degrees)\")])"
241
+ ]
242
+ },
243
+ {
244
+ "cell_type": "code",
245
+ "execution_count": null,
246
+ "id": "82791573",
247
+ "metadata": {},
248
+ "outputs": [],
249
+ "source": [
250
+ "def darken(img, contrast=0.05, brightness=0):\n",
251
+ " return cv2.convertScaleAbs(img, alpha=contrast, beta=brightness)\n",
252
+ "\n",
253
+ "add_step(darken, \"Dark photo\", \"break\", short=\"Dark\",\n",
254
+ " summary=\"Make the photo dim and flat, like a shot in a dark room.\",\n",
255
+ " explain=\"Every pixel is multiplied by the contrast and shifted by the brightness, then clipped to 0..255. \"\n",
256
+ " \"At the default the whole photo is squeezed into the 14 darkest values (0 to 13). Nothing is clipped, \"\n",
257
+ " \"so a fix can stretch it out again, but only those 14 shades survive, so the fixed photo looks \"\n",
258
+ " \"posterized. Pull the brightness below 0 and the shadows clip to pure black: that detail is gone \"\n",
259
+ " \"for good.\",\n",
260
+ " params=[slider(\"contrast\", 0.05, 0.01, 2.0, 0.01), slider(\"brightness\", 0, -128, 128, 1)])"
261
+ ]
262
+ },
263
+ {
264
+ "cell_type": "code",
265
+ "execution_count": null,
266
+ "id": "52cf2bc0",
267
+ "metadata": {},
268
+ "outputs": [],
269
+ "source": [
270
+ "def blur(img, ksize=21):\n",
271
+ " return cv2.GaussianBlur(img, (ksize, ksize), 0)\n",
272
+ "\n",
273
+ "add_step(blur, \"Blur\", \"break\",\n",
274
+ " summary=\"Blur the photo, like a camera out of focus.\",\n",
275
+ " explain=\"Each pixel becomes a weighted average of its neighbours. Fur, edges and texture, which the model \"\n",
276
+ " \"relies on, fade away. The kernel size must be odd so it has a centre pixel.\",\n",
277
+ " params=[slider(\"ksize\", 21, 3, 61, 2, \"kernel size\", odd=True)])"
278
+ ]
279
+ },
280
+ {
281
+ "cell_type": "code",
282
+ "execution_count": null,
283
+ "id": "ad4ad32a",
284
+ "metadata": {},
285
+ "outputs": [],
286
+ "source": [
287
+ "def add_noise(img, sigma=50):\n",
288
+ " rng = np.random.default_rng(0) # fixed seed: the same noise on every run\n",
289
+ " noisy = img.astype(np.float32) + rng.normal(0, sigma, img.shape)\n",
290
+ " return np.clip(noisy, 0, 255).astype(np.uint8)\n",
291
+ "\n",
292
+ "add_step(add_noise, \"Noise\", \"break\",\n",
293
+ " summary=\"Add grain, like a cheap sensor at night.\",\n",
294
+ " explain=\"Random values are added to every pixel. People see straight through the grain; models \"\n",
295
+ " \"often do not.\",\n",
296
+ " params=[slider(\"sigma\", 50, 5, 120, 5, \"noise strength\")])"
297
+ ]
298
+ },
299
+ {
300
+ "cell_type": "code",
301
+ "execution_count": null,
302
+ "id": "2192dff9",
303
+ "metadata": {},
304
+ "outputs": [],
305
+ "source": [
306
+ "def salt_pepper(img, amount=0.1):\n",
307
+ " rng = np.random.default_rng(0) # fixed seed: the same specks on every run\n",
308
+ " hit = rng.random(img.shape[:2]) # one random number per pixel\n",
309
+ " out = img.copy()\n",
310
+ " out[hit < amount / 2] = 0 # pepper: pure black\n",
311
+ " out[hit > 1 - amount / 2] = 255 # salt: pure white\n",
312
+ " return out\n",
313
+ "\n",
314
+ "add_step(salt_pepper, \"Salt & pepper noise\", \"break\", short=\"Salt & pepper\",\n",
315
+ " summary=\"Scatter pure black and white specks, like dust or dead pixels.\",\n",
316
+ " explain=\"A fraction of the pixels (the amount) is replaced by pure black or pure white; the rest are untouched. \"\n",
317
+ " \"Unlike grain, each speck is completely wrong, but the pixels around it are still right.\",\n",
318
+ " params=[slider(\"amount\", 0.1, 0.01, 0.5, 0.01, \"fraction of pixels\")])"
319
+ ]
320
+ },
321
+ {
322
+ "cell_type": "code",
323
+ "execution_count": null,
324
+ "id": "e11748f8",
325
+ "metadata": {},
326
+ "outputs": [],
327
+ "source": [
328
+ "def low_resolution(img, factor=8):\n",
329
+ " h, w = img.shape[:2]\n",
330
+ " small = cv2.resize(img, (max(1, w // factor), max(1, h // factor)), interpolation=cv2.INTER_AREA)\n",
331
+ " return cv2.resize(small, (w, h), interpolation=cv2.INTER_NEAREST)\n",
332
+ "\n",
333
+ "add_step(low_resolution, \"Low resolution\", \"break\", short=\"Low-res\",\n",
334
+ " summary=\"Throw away detail, like a tiny thumbnail blown back up.\",\n",
335
+ " explain=\"The photo is shrunk by the factor, then scaled back to its size. The image is the same size, \"\n",
336
+ " \"but most of the information is gone and the edges turn into blocks.\",\n",
337
+ " params=[slider(\"factor\", 8, 2, 32, 1)])"
338
+ ]
339
+ },
340
+ {
341
+ "cell_type": "markdown",
342
+ "id": "4978f341",
343
+ "metadata": {},
344
+ "source": [
345
+ "## Fix it: enhancement and restoration\n",
346
+ "\n",
347
+ "Classic image processing can undo some damage before the model sees the photo. **Enhancement** makes a photo easier\n",
348
+ "to read (brighter, more contrast, sharper edges). **Restoration** tries to remove a known kind of damage (tilt,\n",
349
+ "noise). They are off in the presets. Break the photo, switch a fix on, and watch how much of the answer comes back.\n",
350
+ "\n",
351
+ "A fix can only use what is left in the pixels. There is no fix for low resolution on purpose: once detail is thrown\n",
352
+ "away, no filter can bring it back."
353
+ ]
354
+ },
355
+ {
356
+ "cell_type": "code",
357
+ "execution_count": null,
358
+ "id": "a7ae4b42",
359
+ "metadata": {},
360
+ "outputs": [],
361
+ "source": [
362
+ "def straighten(img, angle=-45):\n",
363
+ " h, w = img.shape[:2]\n",
364
+ " M = cv2.getRotationMatrix2D((w / 2, h / 2), angle, 1.0)\n",
365
+ " return cv2.warpAffine(img, M, (w, h))\n",
366
+ "\n",
367
+ "add_step(straighten, \"Straighten\", \"fix\", helps=[\"rotate\"],\n",
368
+ " summary=\"Rotate the photo back upright by a known angle.\",\n",
369
+ " explain=\"The same rotation as Rotate, in the other direction: -45 exactly undoes a 45 degree tilt. The animal \"\n",
370
+ " \"is upright again and the answer mostly comes back, but the corners that were cut off by the first \"\n",
371
+ " \"rotation stay black, because those pixels are gone.\",\n",
372
+ " params=[slider(\"angle\", -45, -180, 180, 5, \"angle (degrees)\")])"
373
+ ]
374
+ },
375
+ {
376
+ "cell_type": "code",
377
+ "execution_count": null,
378
+ "id": "3cdff0c6",
379
+ "metadata": {},
380
+ "outputs": [],
381
+ "source": [
382
+ "def gamma(img, gamma=0.5):\n",
383
+ " table = (255 * (np.arange(256) / 255) ** gamma).astype(np.uint8) # new value for each old value\n",
384
+ " return cv2.LUT(img, table)\n",
385
+ "\n",
386
+ "add_step(gamma, \"Gamma correction\", \"fix\", short=\"Gamma\", helps=[\"darken\"],\n",
387
+ " summary=\"Brighten the dark tones much more than the bright ones.\",\n",
388
+ " explain=\"Every value v becomes 255 * (v / 255) ** gamma. With gamma below 1, dark values are lifted a lot and \"\n",
389
+ " \"bright ones barely move, so shadows open up without white areas burning out. On a dark photo it brings \"\n",
390
+ " \"the answer back almost fully, as long as the shadows were not clipped to black.\",\n",
391
+ " params=[slider(\"gamma\", 0.5, 0.2, 3.0, 0.05)])"
392
+ ]
393
+ },
394
+ {
395
+ "cell_type": "code",
396
+ "execution_count": null,
397
+ "id": "4e7b6f73",
398
+ "metadata": {},
399
+ "outputs": [],
400
+ "source": [
401
+ "def equalize(img):\n",
402
+ " ycc = cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb) # Y = brightness, Cr and Cb = color\n",
403
+ " y = cv2.equalizeHist(np.ascontiguousarray(ycc[:, :, 0]))\n",
404
+ " return cv2.cvtColor(np.dstack([y, ycc[:, :, 1], ycc[:, :, 2]]), cv2.COLOR_YCrCb2RGB)\n",
405
+ "\n",
406
+ "add_step(equalize, \"Histogram equalization\", \"fix\", short=\"Equalize\", helps=[\"darken\"],\n",
407
+ " summary=\"Spread the brightness values over the whole 0..255 range.\",\n",
408
+ " explain=\"Each brightness level is moved so that the levels spread out over 0..255, in proportion to how many \"\n",
409
+ " \"pixels have them; the colors are left alone. It cannot invent new levels: a dim photo with only a few \"\n",
410
+ " \"dozen levels comes back with the same few dozen, spread apart (see the gaps in the histogram). \"\n",
411
+ " \"Sometimes that is enough for the model, and sometimes the harsh result makes the answer worse.\")"
412
+ ]
413
+ },
414
+ {
415
+ "cell_type": "code",
416
+ "execution_count": null,
417
+ "id": "64427bd4",
418
+ "metadata": {},
419
+ "outputs": [],
420
+ "source": [
421
+ "def clahe(img, clip=4.0, tiles=8):\n",
422
+ " lab = cv2.cvtColor(img, cv2.COLOR_RGB2LAB) # L = lightness, A and B = color\n",
423
+ " tool = cv2.createCLAHE(clipLimit=clip, tileGridSize=(tiles, tiles))\n",
424
+ " l = tool.apply(np.ascontiguousarray(lab[:, :, 0]))\n",
425
+ " return cv2.cvtColor(np.dstack([l, lab[:, :, 1], lab[:, :, 2]]), cv2.COLOR_LAB2RGB)\n",
426
+ "\n",
427
+ "add_step(clahe, \"CLAHE\", \"fix\", helps=[\"darken\"],\n",
428
+ " summary=\"Equalize contrast tile by tile, with a limit so noise is not blown up.\",\n",
429
+ " explain=\"Contrast Limited Adaptive Histogram Equalization splits the lightness into tiles and equalizes each \"\n",
430
+ " \"one, so a dark corner and a bright sky are both fixed. The clip limit caps how much contrast a tile \"\n",
431
+ " \"may gain, which keeps flat areas from turning into noise. On a dark photo it helps, but a little less \"\n",
432
+ " \"than plain gamma, because each tile is stretched on its own.\",\n",
433
+ " params=[slider(\"clip\", 4.0, 1.0, 8.0, 0.5, \"clip limit\"), slider(\"tiles\", 8, 2, 16, 1, \"tiles per side\")])"
434
+ ]
435
+ },
436
+ {
437
+ "cell_type": "code",
438
+ "execution_count": null,
439
+ "id": "cbfa1e10",
440
+ "metadata": {},
441
+ "outputs": [],
442
+ "source": [
443
+ "def denoise(img, h=8):\n",
444
+ " # Non-local means: average each pixel with pixels whose surrounding 7x7 patch looks alike,\n",
445
+ " # searching a 15x15 window around it.\n",
446
+ " return cv2.fastNlMeansDenoisingColored(np.ascontiguousarray(img), None, h, h, 7, 15)\n",
447
+ "\n",
448
+ "add_step(denoise, \"Non-local means denoise\", \"fix\", short=\"Denoise\", helps=[\"add_noise\"],\n",
449
+ " summary=\"Remove grain by averaging patches that look alike.\",\n",
450
+ " explain=\"For each pixel, similar-looking patches in a 15 by 15 neighbourhood are found and averaged, so random \"\n",
451
+ " \"grain cancels out while edges survive. The photo looks much cleaner, but the model often barely \"\n",
452
+ " \"changes its answer: YOLO gets a few objects back on some photos, and ResNet hardly needs it (a higher \"\n",
453
+ " \"h smooths away the fur it relies on). A cleaner picture for people is not always a better one for a \"\n",
454
+ " \"model. It is the slowest step in the lab.\",\n",
455
+ " params=[slider(\"h\", 8, 3, 40, 1, \"strength\")])"
456
+ ]
457
+ },
458
+ {
459
+ "cell_type": "code",
460
+ "execution_count": null,
461
+ "id": "03bdfff8",
462
+ "metadata": {},
463
+ "outputs": [],
464
+ "source": [
465
+ "def median_filter(img, ksize=5):\n",
466
+ " return cv2.medianBlur(np.ascontiguousarray(img), ksize)\n",
467
+ "\n",
468
+ "add_step(median_filter, \"Median filter\", \"fix\", short=\"Median\", helps=[\"salt_pepper\"],\n",
469
+ " summary=\"Replace each pixel by the middle value of its neighbours.\",\n",
470
+ " explain=\"Sort the pixels in a small square and keep the middle one. A black or white speck is almost never the \"\n",
471
+ " \"middle value, so it simply disappears, while edges stay sharp (unless the specks cover so much of the \"\n",
472
+ " \"photo that they become the middle value). Against grain it is a mixed bag: every pixel is a little \"\n",
473
+ " \"wrong, so YOLO finds a few more objects, but ResNet loses the fur texture it relies on.\",\n",
474
+ " params=[slider(\"ksize\", 5, 3, 15, 2, \"kernel size\", odd=True)])"
475
+ ]
476
+ },
477
+ {
478
+ "cell_type": "code",
479
+ "execution_count": null,
480
+ "id": "99202eb5",
481
+ "metadata": {},
482
+ "outputs": [],
483
+ "source": [
484
+ "def sharpen(img, amount=1.5, sigma=3.0):\n",
485
+ " blurred = cv2.GaussianBlur(img, (0, 0), sigma)\n",
486
+ " return cv2.addWeighted(img, 1 + amount, blurred, -amount, 0) # img + amount * (img - blurred)\n",
487
+ "\n",
488
+ "add_step(sharpen, \"Unsharp mask\", \"fix\", short=\"Sharpen\", helps=[\"blur\"],\n",
489
+ " summary=\"Boost edges by adding back the difference from a blurred copy.\",\n",
490
+ " explain=\"Blur a copy, subtract it from the photo to get only the edges, and add those edges back, amplified. \"\n",
491
+ " \"Edges that are still faintly there become crisp again, so the model gets part of its answer back; \"\n",
492
+ " \"detail the blur fully erased cannot return, and too much sharpening adds bright halos.\",\n",
493
+ " params=[slider(\"amount\", 1.5, 0.0, 5.0, 0.1), slider(\"sigma\", 3.0, 0.5, 10.0, 0.5, \"blur radius\")])"
494
+ ]
495
+ },
496
+ {
497
+ "cell_type": "markdown",
498
+ "id": "fa672082",
499
+ "metadata": {},
500
+ "source": [
501
+ "## Running a pipeline\n",
502
+ "\n",
503
+ "A pipeline is a list of steps: `{\"op\": step id, \"params\": {...}, \"enabled\": True}`. `run_step` runs one;\n",
504
+ "`run_pipeline` runs them all and keeps every intermediate image."
505
+ ]
506
+ },
507
+ {
508
+ "cell_type": "code",
509
+ "execution_count": null,
510
+ "id": "e2d1e672",
511
+ "metadata": {},
512
+ "outputs": [],
513
+ "source": [
514
+ "def clean_params(step_id, params=None):\n",
515
+ " # Fill in defaults and keep every value inside its slider range (kernel sizes stay odd).\n",
516
+ " params = params or {}\n",
517
+ " out = {}\n",
518
+ " for p in STEPS[step_id][\"params\"]:\n",
519
+ " v = params.get(p[\"name\"], p[\"default\"])\n",
520
+ " if p[\"type\"] == \"int\":\n",
521
+ " v = min(p[\"max\"], max(p[\"min\"], int(round(float(v)))))\n",
522
+ " if p.get(\"odd\") and v % 2 == 0:\n",
523
+ " v += 1\n",
524
+ " else:\n",
525
+ " v = min(p[\"max\"], max(p[\"min\"], float(v)))\n",
526
+ " out[p[\"name\"]] = v\n",
527
+ " return out\n",
528
+ "\n",
529
+ "\n",
530
+ "def run_step(img, step_id, params):\n",
531
+ " return STEPS[step_id][\"fn\"](img, **params)\n",
532
+ "\n",
533
+ "\n",
534
+ "def run_pipeline(img, steps):\n",
535
+ " # img: the BGR image from load_image. Returns one (name, image) per step, starting with the input.\n",
536
+ " results = [(\"Load image\", img)]\n",
537
+ " for step in steps:\n",
538
+ " if not step.get(\"enabled\", True):\n",
539
+ " continue\n",
540
+ " img = run_step(img, step[\"op\"], clean_params(step[\"op\"], step.get(\"params\")))\n",
541
+ " results.append((STEPS[step[\"op\"]][\"name\"], img))\n",
542
+ " return results"
543
+ ]
544
+ },
545
+ {
546
+ "cell_type": "markdown",
547
+ "id": "8d258447",
548
+ "metadata": {},
549
+ "source": [
550
+ "## Models\n",
551
+ "\n",
552
+ "**ResNet50** (ImageNet, 1000 classes) classifies. **YOLO11s-seg** (COCO, 80 classes) finds, outlines and names every\n",
553
+ "object. Weights are read from `weights/`, downloaded once by `scripts/fetch_models.py`."
554
+ ]
555
+ },
556
+ {
557
+ "cell_type": "code",
558
+ "execution_count": null,
559
+ "id": "9b1768a7",
560
+ "metadata": {},
561
+ "outputs": [],
562
+ "source": [
563
+ "import os\n",
564
+ "from pathlib import Path\n",
565
+ "\n",
566
+ "HERE = Path(globals().get(\"__file__\", \"image_lab.ipynb\")).resolve().parent # the backend folder\n",
567
+ "WEIGHTS = HERE / \"weights\"\n",
568
+ "os.environ.setdefault(\"TORCH_HOME\", str(WEIGHTS / \"torch\"))\n",
569
+ "os.environ.setdefault(\"YOLO_OFFLINE\", \"1\")\n",
570
+ "\n",
571
+ "import torch\n",
572
+ "from torchvision.models import ResNet50_Weights, resnet50\n",
573
+ "\n",
574
+ "LABELS = ResNet50_Weights.IMAGENET1K_V1.meta[\"categories\"] # the 1000 ImageNet class names\n",
575
+ "\n",
576
+ "\n",
577
+ "def load_resnet50():\n",
578
+ " return resnet50(weights=ResNet50_Weights.IMAGENET1K_V1).eval()\n",
579
+ "\n",
580
+ "\n",
581
+ "def classify_resnet50(img, model):\n",
582
+ " # img: the pipeline's output, which should be float32 (3, 224, 224). It goes in exactly as it is, so a\n",
583
+ " # switched-off step really reaches the model. Returns the probability of every class.\n",
584
+ " x = torch.from_numpy(np.ascontiguousarray(img, dtype=np.float32))[None] # add a batch axis\n",
585
+ " with torch.no_grad():\n",
586
+ " logits = model(x)\n",
587
+ " return logits.softmax(dim=1)[0].numpy()\n",
588
+ "\n",
589
+ "\n",
590
+ "def top_k(probs, k=5):\n",
591
+ " best = np.argsort(probs)[::-1][:k]\n",
592
+ " return [(LABELS[i], round(float(probs[i]), 4)) for i in best]"
593
+ ]
594
+ },
595
+ {
596
+ "cell_type": "code",
597
+ "execution_count": null,
598
+ "id": "f78c18c4",
599
+ "metadata": {},
600
+ "outputs": [],
601
+ "source": [
602
+ "def as_uint8_rgb(img):\n",
603
+ " # Undo float, CHW or gray layouts so any pipeline output can be shown or fed to YOLO.\n",
604
+ " if img.ndim == 3 and img.shape[0] == 3 and img.shape[2] != 3:\n",
605
+ " img = img.transpose(1, 2, 0)\n",
606
+ " if img.dtype != np.uint8:\n",
607
+ " img = cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)\n",
608
+ " if img.ndim == 2:\n",
609
+ " img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)\n",
610
+ " return np.ascontiguousarray(img)"
611
+ ]
612
+ },
613
+ {
614
+ "cell_type": "code",
615
+ "execution_count": null,
616
+ "id": "a84cb348",
617
+ "metadata": {},
618
+ "outputs": [],
619
+ "source": [
620
+ "from ultralytics import YOLO\n",
621
+ "\n",
622
+ "\n",
623
+ "def load_yolo():\n",
624
+ " return YOLO(str(WEIGHTS / \"yolo11s-seg.pt\"))\n",
625
+ "\n",
626
+ "\n",
627
+ "def class_color(class_id):\n",
628
+ " # One fixed color per COCO class, identical on every screen.\n",
629
+ " hue = int(class_id * 0.618 % 1 * 180)\n",
630
+ " rgb = cv2.cvtColor(np.uint8([[[hue, 200, 220]]]), cv2.COLOR_HSV2RGB)[0, 0]\n",
631
+ " return tuple(int(c) for c in rgb)\n",
632
+ "\n",
633
+ "\n",
634
+ "def draw_label(img, text, x, y, color):\n",
635
+ " font, scale, thick = cv2.FONT_HERSHEY_SIMPLEX, max(0.5, img.shape[1] / 1000), 1\n",
636
+ " (tw, th), base = cv2.getTextSize(text, font, scale, thick)\n",
637
+ " x, y = min(max(0, x), img.shape[1] - tw - 6), max(th + base + 4, y)\n",
638
+ " cv2.rectangle(img, (x, y - th - base - 4), (x + tw + 6, y), color, -1)\n",
639
+ " cv2.putText(img, text, (x + 3, y - base - 2), font, scale, (0, 0, 0), thick, cv2.LINE_AA)\n",
640
+ "\n",
641
+ "\n",
642
+ "def segment_yolo(img, model, conf=0.25):\n",
643
+ " # img: RGB uint8 (H, W, 3). Returns an image with every object outlined and named,\n",
644
+ " # and one (class, confidence) per object.\n",
645
+ " result = model.predict(img[:, :, ::-1], conf=conf, verbose=False)[0] # Ultralytics expects BGR\n",
646
+ " overlay = img.copy()\n",
647
+ " instances = []\n",
648
+ " if result.masks is None:\n",
649
+ " return overlay, instances\n",
650
+ " polygons = result.masks.xy\n",
651
+ " classes = [int(c) for c in result.boxes.cls.tolist()]\n",
652
+ " scores = result.boxes.conf.tolist()\n",
653
+ " for polygon, cls in zip(polygons, classes): # fill every mask first, so labels stay on top\n",
654
+ " layer = overlay.copy()\n",
655
+ " cv2.fillPoly(layer, [polygon.astype(np.int32)], class_color(cls))\n",
656
+ " overlay = cv2.addWeighted(layer, 0.45, overlay, 0.55, 0)\n",
657
+ " for polygon, cls, score in zip(polygons, classes, scores):\n",
658
+ " pts = polygon.astype(np.int32)\n",
659
+ " if len(pts) == 0:\n",
660
+ " continue\n",
661
+ " cv2.polylines(overlay, [pts], True, class_color(cls), 2, cv2.LINE_AA)\n",
662
+ " top = pts[pts[:, 1].argmin()]\n",
663
+ " draw_label(overlay, f\"{result.names[cls]} {score:.0%}\", int(top[0]), int(top[1]), class_color(cls))\n",
664
+ " instances.append((result.names[cls], round(score, 3)))\n",
665
+ " return overlay, instances"
666
+ ]
667
+ },
668
+ {
669
+ "cell_type": "markdown",
670
+ "id": "039b1d9c",
671
+ "metadata": {},
672
+ "source": [
673
+ "## The two lines\n",
674
+ "\n",
675
+ "Preparation steps are on; break-it and fix-it steps are off. Switch one on (here: `\"enabled\": True`) to see what\n",
676
+ "breaks, then switch on a fix to see what comes back.\n",
677
+ "\n",
678
+ "`best_fix` names, for each break, the fix that brings the answer back best on the line's default photo (measured,\n",
679
+ "and checked by the tests). The app offers it first. A break that is missing there has no fix that reliably helps on\n",
680
+ "that line: for noise the photo looks cleaner after Denoise, but the answer barely moves."
681
+ ]
682
+ },
683
+ {
684
+ "cell_type": "code",
685
+ "execution_count": null,
686
+ "id": "4a3b7b7b",
687
+ "metadata": {},
688
+ "outputs": [],
689
+ "source": [
690
+ "BREAKS = [{\"op\": op, \"enabled\": False}\n",
691
+ " for op in [\"rotate\", \"darken\", \"blur\", \"add_noise\", \"salt_pepper\", \"low_resolution\"]]\n",
692
+ "FIXES = [{\"op\": op, \"enabled\": False}\n",
693
+ " for op in [\"straighten\", \"gamma\", \"equalize\", \"clahe\", \"denoise\", \"median_filter\", \"sharpen\"]]\n",
694
+ "\n",
695
+ "LINES = [\n",
696
+ " dict(id=\"classify\", name=\"Classify\", model=\"ResNet50\", default_image=\"pet-boxer\",\n",
697
+ " question=\"What animal is this?\",\n",
698
+ " task={\"type\": \"classify\"},\n",
699
+ " best_fix={\"rotate\": \"straighten\", \"darken\": \"gamma\", \"salt_pepper\": \"median_filter\"},\n",
700
+ " steps=[{\"op\": \"bgr_to_rgb\"}, *BREAKS, *FIXES,\n",
701
+ " {\"op\": \"resize_shorter\"}, {\"op\": \"center_crop\"}, {\"op\": \"normalize\"}, {\"op\": \"to_chw\"}]),\n",
702
+ " dict(id=\"segment\", name=\"Segment\", model=\"YOLO11s-seg\", default_image=\"coco-000000000049\",\n",
703
+ " question=\"What objects are here, and how many?\",\n",
704
+ " task={\"type\": \"segment\", \"conf\": 0.25},\n",
705
+ " best_fix={\"rotate\": \"straighten\", \"darken\": \"gamma\", \"blur\": \"sharpen\", \"salt_pepper\": \"median_filter\"},\n",
706
+ " steps=[{\"op\": \"bgr_to_rgb\"}, *BREAKS, *FIXES, {\"op\": \"letterbox\"}]),\n",
707
+ "]"
708
+ ]
709
+ },
710
+ {
711
+ "cell_type": "markdown",
712
+ "id": "a17e515d",
713
+ "metadata": {},
714
+ "source": [
715
+ "## Try it\n",
716
+ "\n",
717
+ "These cells are tagged `demo`: they run here in the notebook, never in the web app."
718
+ ]
719
+ },
720
+ {
721
+ "cell_type": "code",
722
+ "execution_count": null,
723
+ "id": "5675e5ee",
724
+ "metadata": {
725
+ "tags": [
726
+ "demo"
727
+ ]
728
+ },
729
+ "outputs": [],
730
+ "source": [
731
+ "import matplotlib.pyplot as plt\n",
732
+ "\n",
733
+ "\n",
734
+ "def show_steps(results, cols=4):\n",
735
+ " rows = (len(results) + cols - 1) // cols\n",
736
+ " fig, axes = plt.subplots(rows, cols, figsize=(4 * cols, 4 * rows))\n",
737
+ " for ax in np.ravel(axes):\n",
738
+ " ax.axis(\"off\")\n",
739
+ " for ax, (name, img) in zip(np.ravel(axes), results):\n",
740
+ " ax.imshow(as_uint8_rgb(img))\n",
741
+ " ax.set_title(f\"{name}\\n{img.shape} {img.dtype}\", fontsize=9)\n",
742
+ " plt.tight_layout()\n",
743
+ " plt.show()\n",
744
+ "\n",
745
+ "\n",
746
+ "results = run_pipeline(load_image(\"data/pets/boxer.jpg\"), LINES[0][\"steps\"])\n",
747
+ "show_steps(results)"
748
+ ]
749
+ },
750
+ {
751
+ "cell_type": "code",
752
+ "execution_count": null,
753
+ "id": "4cc31c8f",
754
+ "metadata": {
755
+ "tags": [
756
+ "demo"
757
+ ]
758
+ },
759
+ "outputs": [],
760
+ "source": [
761
+ "model = load_resnet50()\n",
762
+ "for label, prob in top_k(classify_resnet50(results[-1][1], model)):\n",
763
+ " print(f\"{prob:6.1%} {label}\")"
764
+ ]
765
+ },
766
+ {
767
+ "cell_type": "code",
768
+ "execution_count": null,
769
+ "id": "171a98ad",
770
+ "metadata": {
771
+ "tags": [
772
+ "demo"
773
+ ]
774
+ },
775
+ "outputs": [],
776
+ "source": [
777
+ "from collections import Counter\n",
778
+ "\n",
779
+ "results = run_pipeline(load_image(\"data/coco/000000000049.jpg\"), LINES[1][\"steps\"])\n",
780
+ "overlay, instances = segment_yolo(results[-1][1], load_yolo())\n",
781
+ "print(Counter(name for name, _ in instances))\n",
782
+ "plt.figure(figsize=(8, 8)); plt.imshow(overlay); plt.axis(\"off\"); plt.show()"
783
+ ]
784
+ }
785
+ ],
786
+ "metadata": {
787
+ "kernelspec": {
788
+ "display_name": "Python (imgdemo)",
789
+ "language": "python",
790
+ "name": "imgdemo"
791
+ },
792
+ "language_info": {
793
+ "name": "python"
794
+ }
795
+ },
796
+ "nbformat": 4,
797
+ "nbformat_minor": 5
798
+ }
packages.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ libgl1
2
+ libglib2.0-0
requirements.txt CHANGED
@@ -1,2 +1,7 @@
1
- gradio
2
- google.generativeai
 
 
 
 
 
 
1
+ # The Space image preinstalls gradio, spaces, huggingface_hub and torch: do not list them here.
2
+ torchvision
3
+ ultralytics
4
+ opencv-python-headless
5
+ numpy
6
+ nbformat
7
+ python-multipart
scripts/fetch_data.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Download the demo images once, so the demo runs offline afterwards.
2
+
3
+ - Classification: one test image per breed from Oxford-IIIT Pet (via the Hugging Face datasets server).
4
+ - Segmentation: multi-object images from Ultralytics' coco128-seg (a 128-image COCO subset with instance
5
+ polygons, which give the ground-truth counts).
6
+
7
+ Every image here was checked: on the clean pipeline, ResNet50 names each pet correctly (87-100%) and
8
+ YOLO11s-seg counts every class in each COCO photo exactly. That way "break it" starts from a right answer.
9
+
10
+ Writes backend/data/manifest.json. Safe to re-run: existing files are skipped.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import io
16
+ import json
17
+ import urllib.parse
18
+ import urllib.request
19
+ import zipfile
20
+ from collections import Counter
21
+ from pathlib import Path
22
+
23
+ DATA = Path(__file__).resolve().parents[1] / "data"
24
+ HF_ROWS = "https://datasets-server.huggingface.co/rows"
25
+ COCO128 = "https://github.com/ultralytics/assets/releases/download/v0.0.0/coco128-seg.zip"
26
+
27
+ PET_BREEDS = { # label index in timm/oxford-iiit-pet -> (file name, the matching ImageNet class)
28
+ 25: ("pug", "pug"), 29: ("samoyed", "Samoyed"), 4: ("beagle", "beagle"),
29
+ 28: ("saint_bernard", "Saint Bernard"), 8: ("boxer", "boxer"), 10: ("chihuahua", "Chihuahua"),
30
+ 23: ("persian", "Persian cat"), 11: ("egyptian_mau", "Egyptian cat"),
31
+ }
32
+
33
+ # coco128-seg images on which YOLO11s-seg counts every class exactly (checked through the Segment line: RGB, letterbox 640, conf 0.25).
34
+ COCO_PICKS = ["000000000049", "000000000074", "000000000143", "000000000597", "000000000136", "000000000599"]
35
+
36
+ COCO_NAMES = [
37
+ "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light",
38
+ "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow",
39
+ "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee",
40
+ "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard",
41
+ "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple",
42
+ "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch",
43
+ "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard",
44
+ "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase",
45
+ "scissors", "teddy bear", "hair drier", "toothbrush",
46
+ ]
47
+
48
+
49
+ def get(url: str) -> bytes:
50
+ req = urllib.request.Request(url, headers={"User-Agent": "image-preprocessing-demo"})
51
+ with urllib.request.urlopen(req, timeout=120) as r:
52
+ return r.read()
53
+
54
+
55
+ def pet_image_urls(wanted: set[int]) -> dict[int, str]:
56
+ """Scan the test split page by page until one image per wanted breed is found."""
57
+ found: dict[int, str] = {}
58
+ for offset in range(0, 3700, 100):
59
+ q = urllib.parse.urlencode({"dataset": "timm/oxford-iiit-pet", "config": "default",
60
+ "split": "test", "offset": offset, "length": 100})
61
+ for r in json.loads(get(f"{HF_ROWS}?{q}"))["rows"]:
62
+ label = r["row"]["label"]
63
+ if label in wanted and label not in found:
64
+ found[label] = r["row"]["image"]["src"]
65
+ if len(found) == len(wanted):
66
+ break
67
+ return found
68
+
69
+
70
+ def fetch_pets() -> list[dict]:
71
+ out = []
72
+ (DATA / "pets").mkdir(parents=True, exist_ok=True)
73
+ missing = {label for label, (breed, _) in PET_BREEDS.items() if not (DATA / "pets" / f"{breed}.jpg").exists()}
74
+ urls = pet_image_urls(missing) if missing else {}
75
+ for label, (breed, imagenet) in PET_BREEDS.items():
76
+ path = DATA / "pets" / f"{breed}.jpg"
77
+ if label in urls:
78
+ path.write_bytes(get(urls[label]))
79
+ print("pets:", breed)
80
+ if not path.exists():
81
+ continue
82
+ out.append({
83
+ "id": f"pet-{breed}", "use_case": "classify", "file": f"pets/{breed}.jpg",
84
+ "title": breed.replace("_", " ").title(), "label": imagenet,
85
+ "license": "CC BY-SA 4.0",
86
+ "source": "Oxford-IIIT Pet Dataset (Parkhi et al., 2012), test split, via huggingface.co/datasets/timm/oxford-iiit-pet",
87
+ })
88
+ return out
89
+
90
+
91
+ def fetch_coco() -> list[dict]:
92
+ (DATA / "coco").mkdir(parents=True, exist_ok=True)
93
+ zf = zipfile.ZipFile(io.BytesIO(get(COCO128)))
94
+ out = []
95
+ for stem in COCO_PICKS:
96
+ labels = next(f for f in zf.namelist() if f.endswith(f"/labels/train2017/{stem}.txt"))
97
+ counts = Counter(COCO_NAMES[int(line.split()[0])] for line in zf.read(labels).decode().splitlines() if line.strip())
98
+ image = next(f for f in zf.namelist() if f.endswith(f"/images/train2017/{stem}.jpg"))
99
+ (DATA / "coco" / f"{stem}.jpg").write_bytes(zf.read(image))
100
+ out.append({
101
+ "id": f"coco-{stem}", "use_case": "segment", "file": f"coco/{stem}.jpg",
102
+ "title": ", ".join(f"{v} {k}" for k, v in counts.most_common()),
103
+ "gt_counts": dict(counts), "license": "COCO annotations CC BY 4.0; images under their Flickr licenses",
104
+ "source": "COCO 2017 via Ultralytics coco128-seg (train2017 subset, so the model has seen these images)",
105
+ })
106
+ print("coco:", stem, dict(counts))
107
+ return out
108
+
109
+
110
+ def main() -> None:
111
+ DATA.mkdir(parents=True, exist_ok=True)
112
+ images = fetch_pets() + fetch_coco()
113
+ (DATA / "manifest.json").write_text(json.dumps({"images": images}, indent=2))
114
+ print(f"wrote manifest with {len(images)} images")
115
+
116
+
117
+ if __name__ == "__main__":
118
+ main()
scripts/fetch_models.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Download model weights once so the demo runs offline: ResNet50 (torchvision, V1 weights) and YOLO11s-seg."""
2
+
3
+ import os
4
+ import urllib.request
5
+ from pathlib import Path
6
+
7
+ WEIGHTS = Path(__file__).resolve().parents[1] / "weights"
8
+ YOLO_URL = "https://github.com/ultralytics/assets/releases/download/v8.3.0/yolo11s-seg.pt"
9
+
10
+
11
+ def main() -> None:
12
+ WEIGHTS.mkdir(exist_ok=True)
13
+ os.environ.setdefault("TORCH_HOME", str(WEIGHTS / "torch"))
14
+ from torchvision.models import ResNet50_Weights, resnet50
15
+
16
+ # V1, not V2: V2 was trained with label smoothing, so even correct answers show only 30-50% confidence.
17
+ resnet50(weights=ResNet50_Weights.IMAGENET1K_V1)
18
+ print("resnet50 ok")
19
+ target = WEIGHTS / "yolo11s-seg.pt"
20
+ if not target.exists():
21
+ urllib.request.urlretrieve(YOLO_URL, target)
22
+ print("yolo11s-seg ok", target.stat().st_size, "bytes")
23
+
24
+
25
+ if __name__ == "__main__":
26
+ main()
server.py ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Web server for the Image Preprocessing Lab.
2
+
3
+ All image logic lives in image_lab.ipynb. This file runs that notebook (skipping cells tagged "demo") and
4
+ serves its functions to the browser. It only adds web plumbing: a gallery, a cache, and image encoding.
5
+
6
+ Run: uvicorn server:app --port 8000 (from the backend folder)
7
+
8
+ Environment:
9
+ ALLOWED_ORIGINS comma-separated origins allowed to call the API (default "*"), e.g. https://your-app.vercel.app
10
+ """
11
+
12
+ import ast
13
+ import hashlib
14
+ import json
15
+ import os
16
+ import re
17
+ import threading
18
+ import time
19
+ from collections import OrderedDict
20
+ from contextlib import asynccontextmanager
21
+ from pathlib import Path
22
+
23
+ import cv2
24
+ import nbformat
25
+ import numpy as np
26
+ from fastapi import Body, FastAPI, File, HTTPException, UploadFile
27
+ from fastapi.middleware.cors import CORSMiddleware
28
+ from fastapi.responses import JSONResponse, Response
29
+
30
+ HERE = Path(__file__).resolve().parent
31
+ DATA = HERE / "data"
32
+ UPLOADS = HERE / "uploads"
33
+ MAX_UPLOAD_BYTES = 10 * 1024 * 1024
34
+ UPLOAD_MAX_SIDE = 1024
35
+
36
+
37
+ # ---------------------------------------------------------------- 1. load the notebook
38
+
39
+ def load_notebook(path):
40
+ """Run every non-demo code cell into one namespace; also keep each function's source text."""
41
+ nb = nbformat.read(path, as_version=4)
42
+ lab = {"__file__": str(path), "__name__": "image_lab"}
43
+ sources = {}
44
+ for i, cell in enumerate(nb.cells):
45
+ if cell.cell_type != "code" or "demo" in cell.metadata.get("tags", []):
46
+ continue
47
+ exec(compile(cell.source, f"{path.name} (cell {i})", "exec"), lab)
48
+ for node in ast.parse(cell.source).body:
49
+ if isinstance(node, ast.FunctionDef):
50
+ sources[node.name] = ast.get_source_segment(cell.source, node)
51
+ return lab, sources
52
+
53
+
54
+ LAB, SOURCES = load_notebook(HERE / "image_lab.ipynb")
55
+ STEPS = LAB["STEPS"]
56
+
57
+
58
+ def step_source(step_id):
59
+ """The step function's source, preceded by any private helper it calls (e.g. _gray)."""
60
+ main = SOURCES[step_id]
61
+ helpers = [SOURCES[n] for n in dict.fromkeys(re.findall(r"\b(_[a-z]\w*)\(", main)) if n in SOURCES]
62
+ return "\n\n\n".join([*helpers, main])
63
+
64
+
65
+ def call_line(step_id, params):
66
+ """The exact call the pipeline makes, e.g. img = rotate(img, angle=45)."""
67
+ args = ["img", *(f"{k}={v!r}" for k, v in params.items())]
68
+ return f"img = {step_id}({', '.join(args)})"
69
+
70
+
71
+ # ---------------------------------------------------------------- 2. images
72
+
73
+ def gallery():
74
+ path = DATA / "manifest.json"
75
+ return json.loads(path.read_text())["images"] if path.exists() else []
76
+
77
+
78
+ def image_meta(image_id):
79
+ if image_id.startswith("upload-") and (UPLOADS / f"{image_id[7:]}.png").exists():
80
+ # Uploads are never listed in the gallery: only the person who uploaded one knows its id.
81
+ return {"id": image_id, "use_case": "upload", "file": str(UPLOADS / f"{image_id[7:]}.png"),
82
+ "title": "Your image", "license": "Your image", "source": "Uploaded"}
83
+ for item in gallery():
84
+ if item["id"] == image_id:
85
+ return item
86
+ raise HTTPException(404, f"No image called {image_id!r}")
87
+
88
+
89
+ def image_path(image_id):
90
+ file = Path(image_meta(image_id)["file"])
91
+ return file if file.is_absolute() else DATA / file
92
+
93
+
94
+ RAW = OrderedDict() # image id -> the BGR array from load_image
95
+
96
+
97
+ def load(image_id):
98
+ if image_id not in RAW:
99
+ if not re.fullmatch(r"[\w-]+", image_id):
100
+ raise HTTPException(404, "Bad image id")
101
+ img = LAB["load_image"](image_path(image_id))
102
+ img.setflags(write=False) # shared by every run: steps must return new arrays
103
+ RAW[image_id] = img
104
+ while len(RAW) > 64:
105
+ RAW.popitem(last=False)
106
+ return RAW[image_id]
107
+
108
+
109
+ # ---------------------------------------------------------------- 3. turning arrays into pictures and numbers
110
+
111
+ def is_chw(a):
112
+ return a.ndim == 3 and a.shape[0] in (1, 3) and a.shape[2] not in (1, 3, 4)
113
+
114
+
115
+ def to_display(a):
116
+ """RGB or gray uint8 for the browser, plus a note when values had to be rescaled to be visible."""
117
+ if is_chw(a):
118
+ a = a.transpose(1, 2, 0)
119
+ if a.dtype == np.uint8:
120
+ return a, None
121
+ lo, hi = float(a.min()), float(a.max())
122
+ scaled = cv2.normalize(a.astype(np.float32), None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
123
+ return scaled, f"{a.dtype} values {lo:.2f} to {hi:.2f}, stretched to 0..255 so you can see them"
124
+
125
+
126
+ def stats(a):
127
+ return {"shape": list(a.shape), "dtype": str(a.dtype), "min": round(float(a.min()), 3),
128
+ "max": round(float(a.max()), 3),
129
+ "layout": "CHW" if is_chw(a) else ("HW" if a.ndim == 2 else "HWC")}
130
+
131
+
132
+ def encode(img, fmt="png", width=None):
133
+ if width and img.shape[1] > width:
134
+ img = cv2.resize(img, (width, round(img.shape[0] * width / img.shape[1])), interpolation=cv2.INTER_AREA)
135
+ bgr = img[:, :, ::-1] if img.ndim == 3 else img
136
+ ok, buf = cv2.imencode("." + fmt, np.ascontiguousarray(bgr), [cv2.IMWRITE_JPEG_QUALITY, 90] if fmt == "jpg" else [])
137
+ return buf.tobytes()
138
+
139
+
140
+ # ---------------------------------------------------------------- 4. running a line, with a cache
141
+
142
+ # Each step result is cached under a key built from the image and every step up to it, so moving one
143
+ # slider only recomputes that step and the ones after it.
144
+ CACHE = OrderedDict() # key -> dict(array, error, ms)
145
+ CACHE_LOCK = threading.Lock()
146
+ MODELS = {}
147
+ MODEL_LOCKS = {"resnet50": threading.Lock(), "yolo": threading.Lock()}
148
+
149
+
150
+ def remember(key, entry):
151
+ with CACHE_LOCK:
152
+ CACHE[key] = entry
153
+ while len(CACHE) > 600:
154
+ CACHE.popitem(last=False) # drop the oldest
155
+ return entry
156
+
157
+
158
+ def recall(key):
159
+ with CACHE_LOCK:
160
+ if key in CACHE:
161
+ CACHE.move_to_end(key)
162
+ return CACHE[key]
163
+ return None
164
+
165
+
166
+ KEY_LOCKS = {} # cache key -> lock, while that result is being computed
167
+
168
+
169
+ def once(key, compute):
170
+ """Recall key, or compute it exactly once even when several requests ask at the same time.
171
+
172
+ A slider drag sends many requests and an aborted fetch does not stop the server's work, so without this the
173
+ same slow step (denoise takes about a second) could run several times in parallel."""
174
+ entry = recall(key)
175
+ if entry is not None:
176
+ return entry
177
+ with CACHE_LOCK:
178
+ lock = KEY_LOCKS.setdefault(key, threading.Lock())
179
+ with lock:
180
+ try:
181
+ entry = recall(key)
182
+ return entry if entry is not None else remember(key, compute())
183
+ finally:
184
+ with CACHE_LOCK:
185
+ KEY_LOCKS.pop(key, None)
186
+
187
+
188
+ def with_model(name, fn):
189
+ """Run fn(model) while holding that model's lock: one inference at a time per model."""
190
+ with MODEL_LOCKS[name]:
191
+ if name not in MODELS:
192
+ MODELS[name] = LAB["load_resnet50"]() if name == "resnet50" else LAB["load_yolo"]()
193
+ return fn(MODELS[name])
194
+
195
+
196
+ def make_key(*parts):
197
+ return hashlib.sha1("|".join(parts).encode()).hexdigest()[:16]
198
+
199
+
200
+ def histogram(display, bins=64):
201
+ """Brightness histogram of the displayed picture: `bins` counts over 0..255."""
202
+ gray = cv2.cvtColor(display, cv2.COLOR_RGB2GRAY) if display.ndim == 3 and display.shape[2] == 3 else display
203
+ if gray.ndim == 3:
204
+ gray = gray[:, :, 0]
205
+ counts = cv2.calcHist([np.ascontiguousarray(gray)], [0], None, [bins], [0, 256])
206
+ return [int(c) for c in counts.ravel()]
207
+
208
+
209
+ def describe(key, entry, **extra):
210
+ if "hist" not in entry: # computed once per cached result
211
+ display, note = to_display(entry["array"])
212
+ entry["hist"], entry["note"] = histogram(display), note
213
+ return {**extra, "key": key, "error": entry.get("error"), "ms": entry.get("ms", 0),
214
+ "stats": stats(entry["array"]), "display_note": entry["note"], "hist": entry["hist"]}
215
+
216
+
217
+ def run_steps(image_id, steps):
218
+ """Run a line's steps through the cache. Returns (final key, final entry, one description per step)."""
219
+ key = make_key("load", image_id)
220
+ current = recall(key) or remember(key, {"array": load(image_id)})
221
+ out = [describe(key, current, uid="load", op="load", name="Load image", kind="load", enabled=True, params={},
222
+ call="img = load_image(path)")]
223
+ for step in steps:
224
+ step_id = step.get("op")
225
+ if step_id not in STEPS:
226
+ continue
227
+ enabled = bool(step.get("enabled", True))
228
+ params = LAB["clean_params"](step_id, step.get("params"))
229
+ key = make_key(key, json.dumps([step_id, params, enabled], sort_keys=True))
230
+ entry = once(key, lambda: compute_step(current, step_id, params, enabled))
231
+ # uid and rev are echoed untouched so the app can tell which step, and which edit, a result belongs to.
232
+ out.append(describe(key, entry, uid=step.get("uid"), rev=step.get("rev"), op=step_id,
233
+ name=STEPS[step_id]["name"], kind=STEPS[step_id]["kind"], enabled=enabled, params=params,
234
+ call=call_line(step_id, params)))
235
+ current = entry
236
+ return key, current, out
237
+
238
+
239
+ def compute_step(current, step_id, params, enabled):
240
+ if not enabled:
241
+ return {"array": current["array"]}
242
+ t0 = time.perf_counter()
243
+ try:
244
+ entry = {"array": np.asarray(LAB["run_step"](current["array"], step_id, params))}
245
+ except Exception as exc: # show the error on the step; the image passes through unchanged
246
+ msg = str(exc).strip().splitlines()[-1] if str(exc).strip() else ""
247
+ entry = {"array": current["array"], "error": f"{type(exc).__name__}: {msg}"}
248
+ entry["ms"] = round((time.perf_counter() - t0) * 1000, 1)
249
+ return entry
250
+
251
+
252
+ def clean_version(steps):
253
+ """The same line with every preparation step on at its defaults and every break-it and fix-it step off."""
254
+ return [{"op": s.get("op"), "enabled": STEPS[s["op"]]["kind"] == "prep"} for s in steps if s.get("op") in STEPS]
255
+
256
+
257
+ def run_line(image_id, steps, task):
258
+ key, final, out = run_steps(image_id, steps)
259
+ result = run_task(task, key, final)
260
+ if result is not None:
261
+ bkey, bfinal, _ = run_steps(image_id, clean_version(steps))
262
+ result["baseline"] = run_task(task, bkey, bfinal)
263
+ if result["type"] == "classify":
264
+ # How sure the model is NOW of what it answered on the clean image: this is what drops.
265
+ base, pk = result["baseline"], result["probs_key"]
266
+ result["baseline_label_now"] = None
267
+ if base["top5"] and pk in CACHE_PROBS:
268
+ label = base["top5"][0]["label"]
269
+ result["baseline_label_now"] = round(float(CACHE_PROBS[pk][LAB["LABELS"].index(label)]), 4)
270
+ return {"image": image_meta(image_id), "steps": out, "result": result}
271
+
272
+
273
+ CACHE_PROBS = {} # probs key -> the 1000 class probabilities (small, kept apart from the image cache)
274
+
275
+
276
+ def run_task(task, key, final):
277
+ kind = (task or {}).get("type", "none")
278
+ if kind == "classify":
279
+ rkey = make_key(key, "classify")
280
+ cached = recall(rkey)
281
+ if cached is None:
282
+ t0 = time.perf_counter()
283
+ a = final["array"]
284
+ result = {"type": "classify", "model": "ResNet50", "input_shape": [1, *a.shape], "input_dtype": str(a.dtype),
285
+ "input_range": [round(float(a.min()), 2), round(float(a.max()), 2)], "probs_key": rkey,
286
+ "error": None, "top5": []}
287
+ try:
288
+ probs = with_model("resnet50", lambda m: LAB["classify_resnet50"](a, m))
289
+ CACHE_PROBS[rkey] = probs
290
+ while len(CACHE_PROBS) > 2000:
291
+ CACHE_PROBS.pop(next(iter(CACHE_PROBS)))
292
+ result["top5"] = [{"label": label, "prob": p} for label, p in LAB["top_k"](probs, 5)]
293
+ except Exception as exc: # e.g. channels last: PyTorch refuses, and that is the lesson
294
+ msg = str(exc).strip().splitlines()[0] if str(exc).strip() else type(exc).__name__
295
+ result["error"] = msg
296
+ result["probs_key"] = None
297
+ result["ms"] = round((time.perf_counter() - t0) * 1000, 1)
298
+ cached = remember(rkey, {"array": a, "result": result})
299
+ pk = cached["result"]["probs_key"]
300
+ if pk is not None and pk not in CACHE_PROBS: # evicted: recompute on the next run
301
+ with CACHE_LOCK:
302
+ CACHE.pop(rkey, None)
303
+ return run_task(task, key, final)
304
+ return dict(cached["result"])
305
+ if kind == "segment":
306
+ conf = min(0.95, max(0.05, float(task.get("conf", 0.25))))
307
+ rkey = make_key(key, "segment", f"{conf:.3f}")
308
+ cached = recall(rkey)
309
+ if cached is None:
310
+ t0 = time.perf_counter()
311
+ img = LAB["as_uint8_rgb"](final["array"])
312
+ overlay, instances = with_model("yolo", lambda m: LAB["segment_yolo"](img, m, conf))
313
+ counts = {}
314
+ for name, _ in instances:
315
+ counts[name] = counts.get(name, 0) + 1
316
+ # class name -> the mask color segment_yolo drew, so the app's legend matches the picture
317
+ colors = {n: "#%02x%02x%02x" % LAB["class_color"](i) for i, n in MODELS["yolo"].names.items()}
318
+ cached = remember(rkey, {"array": overlay, "result": {
319
+ "type": "segment", "model": "YOLO11s-seg", "conf": conf, "total": len(instances),
320
+ "counts": dict(sorted(counts.items(), key=lambda kv: -kv[1])), "overlay_key": rkey,
321
+ "colors": colors,
322
+ "instances": [{"label": n, "conf": c} for n, c in instances], "input_shape": list(img.shape),
323
+ "notes": [] if final["array"].dtype == np.uint8 else ["The pipeline output was converted to uint8 RGB first."],
324
+ "ms": round((time.perf_counter() - t0) * 1000, 1)}})
325
+ return dict(cached["result"])
326
+ return None
327
+
328
+
329
+ # ---------------------------------------------------------------- 5. HTTP routes
330
+
331
+ def warm_up():
332
+ """Load both models, then run every gallery image through its clean line, so first clicks are instant."""
333
+ with_model("resnet50", lambda m: LAB["classify_resnet50"](np.zeros((3, 224, 224), np.float32), m))
334
+ with_model("yolo", lambda m: LAB["segment_yolo"](np.zeros((640, 640, 3), np.uint8), m))
335
+ lines = {line["id"]: line for line in LAB["LINES"]}
336
+ for item in gallery():
337
+ line = lines[item["use_case"]]
338
+ try:
339
+ run_line(item["id"], line["steps"], line["task"])
340
+ except Exception as exc: # a missing file should not stop the server
341
+ print("warm-up skipped", item["id"], exc)
342
+ # The default photo is what the presenter breaks and fixes first: run every break, alone and with each fix
343
+ # meant for it (denoise takes about a second), so those first clicks are instant too.
344
+ for line in LAB["LINES"]:
345
+ for s in line["steps"]:
346
+ if STEPS.get(s["op"], {}).get("kind") != "break":
347
+ continue
348
+ fixes = [f for f, d in STEPS.items() if d["kind"] == "fix" and s["op"] in d["helps"]]
349
+ for on in [{s["op"]}, *({s["op"], f} for f in fixes)]:
350
+ steps = [{**x, "enabled": True} if x["op"] in on else x for x in line["steps"]]
351
+ try:
352
+ run_line(line["default_image"], steps, line["task"])
353
+ except Exception as exc:
354
+ print("warm-up skipped", line["id"], sorted(on), exc)
355
+
356
+
357
+ @asynccontextmanager
358
+ async def lifespan(_):
359
+ threading.Thread(target=warm_up, daemon=True).start()
360
+ yield
361
+
362
+
363
+ app = FastAPI(title="Image Preprocessing Lab", lifespan=lifespan)
364
+ app.add_middleware(CORSMiddleware, allow_origins=[o.strip() for o in os.environ.get("ALLOWED_ORIGINS", "*").split(",")],
365
+ allow_methods=["GET", "POST"], allow_headers=["*"])
366
+ FOREVER = {"Cache-Control": "public, max-age=31536000, immutable"}
367
+
368
+
369
+ @app.get("/api/health")
370
+ def health():
371
+ return {"ok": True, "models_ready": len(MODELS) == 2}
372
+
373
+
374
+ @app.get("/api/steps")
375
+ def steps():
376
+ return {
377
+ "kinds": LAB["KINDS"],
378
+ "steps": [{k: v for k, v in s.items() if k != "fn"} | {"source": step_source(s["id"])} for s in STEPS.values()],
379
+ "load_source": SOURCES["load_image"],
380
+ "model_sources": {"classify": "\n\n\n".join(SOURCES[n] for n in ("classify_resnet50", "top_k")),
381
+ "segment": "\n\n\n".join(SOURCES[n] for n in ("draw_label", "segment_yolo"))},
382
+ }
383
+
384
+
385
+ @app.get("/api/lines")
386
+ def lines():
387
+ return {"lines": LAB["LINES"]}
388
+
389
+
390
+ @app.get("/api/images")
391
+ def images():
392
+ return {"images": gallery()}
393
+
394
+
395
+ @app.get("/api/images/{image_id}/thumb")
396
+ def image_thumb(image_id: str):
397
+ return Response(encode(load(image_id)[:, :, ::-1], "jpg", width=320), media_type="image/jpeg", headers=FOREVER)
398
+
399
+
400
+ @app.post("/api/upload")
401
+ async def upload(file: UploadFile = File(...)):
402
+ data = await file.read(MAX_UPLOAD_BYTES + 1)
403
+ if len(data) > MAX_UPLOAD_BYTES:
404
+ raise HTTPException(413, "Images up to 10 MB, please.")
405
+ arr = cv2.imdecode(np.frombuffer(data, np.uint8), cv2.IMREAD_COLOR)
406
+ if arr is None:
407
+ raise HTTPException(400, "That file is not an image OpenCV can read.")
408
+ h, w = arr.shape[:2]
409
+ s = UPLOAD_MAX_SIDE / max(h, w)
410
+ if s < 1:
411
+ arr = cv2.resize(arr, (round(w * s), round(h * s)), interpolation=cv2.INTER_AREA)
412
+ UPLOADS.mkdir(exist_ok=True)
413
+ digest = hashlib.sha1(data).hexdigest()[:12]
414
+ cv2.imwrite(str(UPLOADS / f"{digest}.png"), arr)
415
+ return {"id": f"upload-{digest}"}
416
+
417
+
418
+ @app.post("/api/run")
419
+ def run(body: dict = Body(...)):
420
+ return run_line(str(body["image"]), body.get("steps", []), body.get("task", {}))
421
+
422
+
423
+ @app.get("/api/img/{key}")
424
+ def step_image(key: str, w: int | None = None):
425
+ entry = recall(key)
426
+ if entry is None:
427
+ raise HTTPException(404, "Image expired from the cache; run the line again")
428
+ display, _ = to_display(entry["array"])
429
+ if w:
430
+ return Response(encode(display, "jpg", width=min(w, 2048)), media_type="image/jpeg", headers=FOREVER)
431
+ return Response(encode(display, "png"), media_type="image/png", headers=FOREVER)
432
+
433
+
434
+ @app.exception_handler(Exception)
435
+ def crash(_, exc):
436
+ return JSONResponse({"detail": f"{type(exc).__name__}: {exc}"}, status_code=500)
static/assets/bricolage-grotesque-latin-ext-wght-normal-CcLUaPy7.woff2 ADDED
Binary file (18.7 kB). View file
 
static/assets/bricolage-grotesque-latin-wght-normal-DLoelf7F.woff2 ADDED
Binary file (41.3 kB). View file
 
static/assets/bricolage-grotesque-vietnamese-wght-normal-BUzh504Q.woff2 ADDED
Binary file (8.61 kB). View file
 
static/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 ADDED
Binary file (7.42 kB). View file
 
static/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 ADDED
Binary file (15.1 kB). View file
 
static/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 ADDED
Binary file (16.5 kB). View file
 
static/assets/geist-latin-wght-normal-BgDaEnEv.woff2 ADDED
Binary file (29.4 kB). View file
 
static/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 ADDED
Binary file (6.18 kB). View file
 
static/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 ADDED
Binary file (12.9 kB). View file
 
static/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 ADDED
Binary file (14.7 kB). View file
 
static/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 ADDED
Binary file (23.1 kB). View file
 
static/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 ADDED
Binary file (5.81 kB). View file
 
static/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 ADDED
Binary file (7.7 kB). View file
 
static/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 ADDED
Binary file (8 kB). View file
 
static/assets/index-3TAydZ6P.js ADDED
The diff for this file is too large to render. See raw diff
 
static/assets/index-BRWcS88i.css ADDED
@@ -0,0 +1 @@
 
 
1
+ @font-face{font-family:Bricolage Grotesque Variable;font-style:normal;font-display:swap;font-weight:200 800;src:url(/assets/bricolage-grotesque-vietnamese-wght-normal-BUzh504Q.woff2)format("woff2-variations");unicode-range:U+102-103,U+110-111,U+128-129,U+168-169,U+1A0-1A1,U+1AF-1B0,U+300-301,U+303-304,U+308-309,U+323,U+329,U+1EA0-1EF9,U+20AB}@font-face{font-family:Bricolage Grotesque Variable;font-style:normal;font-display:swap;font-weight:200 800;src:url(/assets/bricolage-grotesque-latin-ext-wght-normal-CcLUaPy7.woff2)format("woff2-variations");unicode-range:U+100-2BA,U+2BD-2C5,U+2C7-2CC,U+2CE-2D7,U+2DD-2FF,U+304,U+308,U+329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:Bricolage Grotesque Variable;font-style:normal;font-display:swap;font-weight:200 800;src:url(/assets/bricolage-grotesque-latin-wght-normal-DLoelf7F.woff2)format("woff2-variations");unicode-range:U+??,U+131,U+152-153,U+2BB-2BC,U+2C6,U+2DA,U+2DC,U+304,U+308,U+329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2)format("woff2-variations");unicode-range:U+460-52F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2)format("woff2-variations");unicode-range:U+301,U+400-45F,U+490-491,U+4B0-4B1,U+2116}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2)format("woff2-variations");unicode-range:U+102-103,U+110-111,U+128-129,U+168-169,U+1A0-1A1,U+1AF-1B0,U+300-301,U+303-304,U+308-309,U+323,U+329,U+1EA0-1EF9,U+20AB}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2)format("woff2-variations");unicode-range:U+100-2BA,U+2BD-2C5,U+2C7-2CC,U+2CE-2D7,U+2DD-2FF,U+304,U+308,U+329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-wght-normal-BgDaEnEv.woff2)format("woff2-variations");unicode-range:U+??,U+131,U+152-153,U+2BB-2BC,U+2C6,U+2DA,U+2DC,U+304,U+308,U+329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@font-face{font-family:Geist Mono Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2)format("woff2-variations");unicode-range:U+460-52F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F}@font-face{font-family:Geist Mono Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2)format("woff2-variations");unicode-range:U+301,U+400-45F,U+490-491,U+4B0-4B1,U+2116}@font-face{font-family:Geist Mono Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2)format("woff2-variations");unicode-range:U+2000-2001,U+2004-2008,U+200A,U+23B8-23BD,U+2500-259F}@font-face{font-family:Geist Mono Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2)format("woff2-variations");unicode-range:U+102-103,U+110-111,U+128-129,U+168-169,U+1A0-1A1,U+1AF-1B0,U+300-301,U+303-304,U+308-309,U+323,U+329,U+1EA0-1EF9,U+20AB}@font-face{font-family:Geist Mono Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2)format("woff2-variations");unicode-range:U+100-2BA,U+2BD-2C5,U+2C7-2CC,U+2CE-2D7,U+2DD-2FF,U+304,U+308,U+329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:Geist Mono Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2)format("woff2-variations");unicode-range:U+??,U+131,U+152-153,U+2BB-2BC,U+2C6,U+2DA,U+2DC,U+304,U+308,U+329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial}}}@layer theme{:root,:host{--font-sans:"Geist Variable", ui-sans-serif, system-ui, sans-serif;--font-mono:"Geist Mono Variable", ui-monospace, "SF Mono", monospace;--color-black:#000;--color-white:#fff;--spacing:.25rem;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--tracking-wide:.025em;--leading-tight:1.25;--leading-snug:1.375;--leading-relaxed:1.625;--radius-sm:.25rem;--radius-md:.375rem;--radius-lg:.5rem;--radius-xl:.75rem;--radius-2xl:1rem;--ease-out:cubic-bezier(.22, 1, .36, 1);--animate-pulse:pulse 2s cubic-bezier(.4, 0, .6, 1) infinite;--blur-md:12px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--font-display:"Bricolage Grotesque Variable", "Geist Variable", ui-sans-serif, sans-serif;--color-ground:oklch(98.5% .002 260);--color-surface:#fff;--color-sunken:oklch(96.2% .004 260);--color-ink:oklch(20% .01 260);--color-ink-2:oklch(42% .01 260);--color-ink-3:oklch(55% .01 260);--color-rule:oklch(20% .01 260/.1);--color-rule-strong:oklch(20% .01 260/.2);--color-classify:oklch(55% .21 262);--color-classify-soft:oklch(94.5% .04 262);--color-segment:oklch(55% .23 340);--color-segment-soft:oklch(95% .035 340);--color-break:oklch(62% .17 45);--color-break-soft:oklch(96% .035 60);--color-break-ink:oklch(45% .14 45);--color-fix:oklch(53% .13 165);--color-fix-soft:oklch(95.5% .04 165);--color-fix-ink:oklch(40% .1 165);--color-good:oklch(52% .14 150);--color-bad:oklch(55% .2 25);--color-bad-soft:oklch(96% .025 25);--radius-card:24px;--shadow-card:0 1px 2px oklch(20% .02 280/.05), 0 10px 30px -8px oklch(40% .08 280/.14);--ease-spring:cubic-bezier(.34, 1.56, .64, 1)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.pointer-events-none{pointer-events:none}.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.inset-0{inset:0}.inset-x-0{inset-inline:0}.inset-y-0{inset-block:0}.top-0{top:0}.top-0\.5{top:calc(var(--spacing) * .5)}.top-1{top:var(--spacing)}.top-1\/2{top:50%}.top-3{top:calc(var(--spacing) * 3)}.top-13{top:calc(var(--spacing) * 13)}.right-0{right:0}.right-1{right:var(--spacing)}.right-3{right:calc(var(--spacing) * 3)}.bottom-0{bottom:0}.bottom-1{bottom:var(--spacing)}.bottom-5{bottom:calc(var(--spacing) * 5)}.left-0\.5{left:calc(var(--spacing) * .5)}.left-1{left:var(--spacing)}.left-1\/2{left:50%}.left-3{left:calc(var(--spacing) * 3)}.z-20{z-index:20}.z-30{z-index:30}.z-40{z-index:40}.z-50{z-index:50}.m-0{margin:0}.mx-3{margin-inline:calc(var(--spacing) * 3)}.mx-4{margin-inline:calc(var(--spacing) * 4)}.mx-auto{margin-inline:auto}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mt-1{margin-top:var(--spacing)}.mt-1\.5{margin-top:calc(var(--spacing) * 1.5)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-2\.5{margin-top:calc(var(--spacing) * 2.5)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mt-6{margin-top:calc(var(--spacing) * 6)}.mr-2{margin-right:calc(var(--spacing) * 2)}.mb-1{margin-bottom:var(--spacing)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.ml-1\.5{margin-left:calc(var(--spacing) * 1.5)}.ml-auto{margin-left:auto}.line-clamp-2{-webkit-line-clamp:2;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.aspect-square{aspect-ratio:1}.size-3{width:calc(var(--spacing) * 3);height:calc(var(--spacing) * 3)}.size-3\.5{width:calc(var(--spacing) * 3.5);height:calc(var(--spacing) * 3.5)}.size-6{width:calc(var(--spacing) * 6);height:calc(var(--spacing) * 6)}.size-8{width:calc(var(--spacing) * 8);height:calc(var(--spacing) * 8)}.size-9{width:calc(var(--spacing) * 9);height:calc(var(--spacing) * 9)}.size-full{width:100%;height:100%}.h-1\.5{height:calc(var(--spacing) * 1.5)}.h-2{height:calc(var(--spacing) * 2)}.h-6{height:calc(var(--spacing) * 6)}.h-7{height:calc(var(--spacing) * 7)}.h-8{height:calc(var(--spacing) * 8)}.h-10{height:calc(var(--spacing) * 10)}.h-11{height:calc(var(--spacing) * 11)}.h-\[3px\]{height:3px}.h-\[64px\]{height:64px}.h-full{height:100%}.min-h-0{min-height:0}.min-h-\[40px\]{min-height:40px}.min-h-\[160px\]{min-height:160px}.min-h-\[260px\]{min-height:260px}.min-h-\[440px\]{min-height:440px}.w-1\/3{width:33.3333%}.w-12{width:calc(var(--spacing) * 12)}.w-48{width:calc(var(--spacing) * 48)}.w-\[3px\]{width:3px}.w-\[136px\]{width:136px}.w-\[min\(520px\,calc\(100vw-32px\)\)\]{width:min(520px,100vw - 32px)}.w-\[min\(600px\,100vw\)\]{width:min(600px,100vw)}.w-full{width:100%}.max-w-28{max-width:calc(var(--spacing) * 28)}.max-w-\[520px\]{max-width:520px}.min-w-0{min-width:0}.min-w-6{min-width:calc(var(--spacing) * 6)}.min-w-7{min-width:calc(var(--spacing) * 7)}.min-w-\[4\.5rem\]{min-width:4.5rem}.min-w-\[100px\]{min-width:100px}.flex-1{flex:1}.flex-\[1_1_18rem\]{flex:18rem}.shrink-0{flex-shrink:0}.origin-bottom-right{transform-origin:100% 100%}.-translate-1\/2{--tw-translate-x:calc(calc(1 / 2 * 100%) * -1);--tw-translate-y:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.-translate-x-1\/2{--tw-translate-x:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.scale-\[0\.72\]{scale:.72}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.animate-pulse{animation:var(--animate-pulse)}.cursor-pointer{cursor:pointer}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.grid-cols-\[minmax\(0\,8\.5rem\)_minmax\(0\,1fr\)_3\.25rem\]{grid-template-columns:minmax(0,8.5rem) minmax(0,1fr) 3.25rem}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-baseline{align-items:baseline}.items-center{align-items:center}.items-start{align-items:flex-start}.items-stretch{align-items:stretch}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.gap-0\.5{gap:calc(var(--spacing) * .5)}.gap-1{gap:var(--spacing)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-6{gap:calc(var(--spacing) * 6)}.gap-px{gap:1px}.gap-x-1\.5{column-gap:calc(var(--spacing) * 1.5)}.gap-x-3{column-gap:calc(var(--spacing) * 3)}.gap-x-4{column-gap:calc(var(--spacing) * 4)}.gap-x-6{column-gap:calc(var(--spacing) * 6)}.gap-y-1\.5{row-gap:calc(var(--spacing) * 1.5)}.gap-y-2{row-gap:calc(var(--spacing) * 2)}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-full{border-radius:2147483647px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-sm{border-radius:var(--radius-sm)}.rounded-xl{border-radius:var(--radius-xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-\[3px\]{border-style:var(--tw-border-style);border-width:3px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-l-2{border-left-style:var(--tw-border-style);border-left-width:2px}.border-dashed{--tw-border-style:dashed;border-style:dashed}.border-\(--accent\){border-color:var(--accent)}.border-\[oklch\(30\%_0\.01_260\)\]{border-color:oklch(30% .01 260)}.border-break{border-color:var(--color-break)}.border-fix{border-color:var(--color-fix)}.border-fix\/35{border-color:#00805b59}@supports (color:color-mix(in lab, red, red)){.border-fix\/35{border-color:color-mix(in oklab, var(--color-fix) 35%, transparent)}}.border-rule{border-color:var(--color-rule)}.border-rule-strong{border-color:var(--color-rule-strong)}.bg-\(--accent\),.bg-\(--accent\)\/10{background-color:var(--accent)}@supports (color:color-mix(in lab, red, red)){.bg-\(--accent\)\/10{background-color:color-mix(in oklab, var(--accent) 10%, transparent)}}.bg-\(--accent-soft\){background-color:var(--accent-soft)}.bg-\[oklch\(55\%_0\.01_260\/0\.3\)\]{background-color:oklch(55% .01 260/.3)}.bg-bad-soft{background-color:var(--color-bad-soft)}.bg-black\/20{background-color:#0003}@supports (color:color-mix(in lab, red, red)){.bg-black\/20{background-color:color-mix(in oklab, var(--color-black) 20%, transparent)}}.bg-black\/60{background-color:#0009}@supports (color:color-mix(in lab, red, red)){.bg-black\/60{background-color:color-mix(in oklab, var(--color-black) 60%, transparent)}}.bg-break{background-color:var(--color-break)}.bg-break-soft{background-color:var(--color-break-soft)}.bg-fix{background-color:var(--color-fix)}.bg-fix-soft{background-color:var(--color-fix-soft)}.bg-ink{background-color:var(--color-ink)}.bg-sunken{background-color:var(--color-sunken)}.bg-sunken\/60{background-color:#f1f2f599}@supports (color:color-mix(in lab, red, red)){.bg-sunken\/60{background-color:color-mix(in oklab, var(--color-sunken) 60%, transparent)}}.bg-surface{background-color:var(--color-surface)}.bg-surface\/75{background-color:#ffffffbf}@supports (color:color-mix(in lab, red, red)){.bg-surface\/75{background-color:color-mix(in oklab, var(--color-surface) 75%, transparent)}}.bg-white{background-color:var(--color-white)}.bg-linear-to-r{--tw-gradient-position:to right}@supports (background-image:linear-gradient(in lab, red, red)){.bg-linear-to-r{--tw-gradient-position:to right in oklab}}.bg-linear-to-r{background-image:linear-gradient(var(--tw-gradient-stops))}.bg-linear-to-t{--tw-gradient-position:to top}@supports (background-image:linear-gradient(in lab, red, red)){.bg-linear-to-t{--tw-gradient-position:to top in oklab}}.bg-linear-to-t{background-image:linear-gradient(var(--tw-gradient-stops))}.from-black{--tw-gradient-from:var(--color-black);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-black\/70{--tw-gradient-from:#000000b3}@supports (color:color-mix(in lab, red, red)){.from-black\/70{--tw-gradient-from:color-mix(in oklab, var(--color-black) 70%, transparent)}}.from-black\/70{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-transparent{--tw-gradient-to:transparent;--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-white{--tw-gradient-to:var(--color-white);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.object-cover{object-fit:cover}.p-1{padding:var(--spacing)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.px-1{padding-inline:var(--spacing)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-5{padding-inline:calc(var(--spacing) * 5)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:var(--spacing)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-3{padding-block:calc(var(--spacing) * 3)}.pt-2{padding-top:calc(var(--spacing) * 2)}.pt-2\.5{padding-top:calc(var(--spacing) * 2.5)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pt-4{padding-top:calc(var(--spacing) * 4)}.pr-2\.5{padding-right:calc(var(--spacing) * 2.5)}.pr-3{padding-right:calc(var(--spacing) * 3)}.pb-1{padding-bottom:var(--spacing)}.pb-2{padding-bottom:calc(var(--spacing) * 2)}.pb-3{padding-bottom:calc(var(--spacing) * 3)}.pb-3\.5{padding-bottom:calc(var(--spacing) * 3.5)}.pl-1{padding-left:var(--spacing)}.pl-1\.5{padding-left:calc(var(--spacing) * 1.5)}.pl-2{padding-left:calc(var(--spacing) * 2)}.text-center{text-align:center}.text-left{text-align:left}.text-right{text-align:right}.align-middle{vertical-align:middle}.font-mono{font-family:var(--font-mono)}.font-sans{font-family:var(--font-sans)}.text-\[13px\]{font-size:13px}.text-\[14px\]{font-size:14px}.text-\[15px\]{font-size:15px}.text-\[16px\]{font-size:16px}.text-\[17px\]{font-size:17px}.text-\[18px\]{font-size:18px}.text-\[19px\]{font-size:19px}.text-\[20px\]{font-size:20px}.text-\[22px\]{font-size:22px}.text-\[26px\]{font-size:26px}.text-\[28px\]{font-size:28px}.text-\[36px\]{font-size:36px}.text-\[46px\]{font-size:46px}.leading-5{--tw-leading:calc(var(--spacing) * 5);line-height:calc(var(--spacing) * 5)}.leading-\[1\.2\]{--tw-leading:1.2;line-height:1.2}.leading-none{--tw-leading:1;line-height:1}.leading-relaxed{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.leading-snug{--tw-leading:var(--leading-snug);line-height:var(--leading-snug)}.leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-wide{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.hyphens-auto{-webkit-hyphens:auto;hyphens:auto}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.text-\(--accent\){color:var(--accent)}.text-bad{color:var(--color-bad)}.text-break-ink{color:var(--color-break-ink)}.text-fix-ink{color:var(--color-fix-ink)}.text-good{color:var(--color-good)}.text-ink{color:var(--color-ink)}.text-ink-2{color:var(--color-ink-2)}.text-ink-3{color:var(--color-ink-3)}.text-white{color:var(--color-white)}.uppercase{text-transform:uppercase}.line-through{text-decoration-line:line-through}.opacity-30{opacity:.3}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-2xl{--tw-shadow:0 25px 50px -12px var(--tw-shadow-color,#00000040);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-\[0_0_0_1px_rgb\(0_0_0\/0\.25\)\]{--tw-shadow:0 0 0 1px var(--tw-shadow-color,#00000040);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-md{--tw-shadow:0 4px 6px -1px var(--tw-shadow-color,#0000001a), 0 2px 4px -2px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-1{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-2{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-3{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-\(--accent\){--tw-ring-color:var(--accent)}.ring-break\/40{--tw-ring-color:#d55c1366}@supports (color:color-mix(in lab, red, red)){.ring-break\/40{--tw-ring-color:color-mix(in oklab, var(--color-break) 40%, transparent)}}.ring-fix\/40{--tw-ring-color:#00805b66}@supports (color:color-mix(in lab, red, red)){.ring-fix\/40{--tw-ring-color:color-mix(in oklab, var(--color-fix) 40%, transparent)}}.ring-rule{--tw-ring-color:var(--color-rule)}.ring-offset-2{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.blur{--tw-blur:blur(8px);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.grayscale{--tw-grayscale:grayscale(100%);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.backdrop-blur-md{--tw-backdrop-blur:blur(var(--blur-md));-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.transition-\[width\]{transition-property:width;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-shadow{transition-property:box-shadow;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-200{--tw-duration:.2s;transition-duration:.2s}.duration-500{--tw-duration:.5s;transition-duration:.5s}.ease-\(--ease-out\){--tw-ease:var(--ease-out);transition-timing-function:var(--ease-out)}.select-none{-webkit-user-select:none;user-select:none}@media (hover:hover){.hover\:border-\(--accent\):hover{border-color:var(--accent)}.hover\:border-fix:hover{border-color:var(--color-fix)}.hover\:border-ink-3:hover{border-color:var(--color-ink-3)}.hover\:bg-sunken:hover{background-color:var(--color-sunken)}.hover\:bg-sunken\/60:hover{background-color:#f1f2f599}@supports (color:color-mix(in lab, red, red)){.hover\:bg-sunken\/60:hover{background-color:color-mix(in oklab, var(--color-sunken) 60%, transparent)}}.hover\:text-ink:hover{color:var(--color-ink)}.hover\:opacity-90:hover{opacity:.9}.hover\:shadow-md:hover{--tw-shadow:0 4px 6px -1px var(--tw-shadow-color,#0000001a), 0 2px 4px -2px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}}.disabled\:cursor-default:disabled{cursor:default}.disabled\:opacity-40:disabled{opacity:.4}@media (hover:hover){.disabled\:hover\:bg-surface:disabled:hover{background-color:var(--color-surface)}}@media (width>=40rem){.sm\:inline{display:inline}.sm\:max-w-44{max-width:calc(var(--spacing) * 44)}.sm\:gap-5{gap:calc(var(--spacing) * 5)}.sm\:p-5{padding:calc(var(--spacing) * 5)}}@media (width>=48rem){.md\:h-\[72px\]{height:72px}.md\:flex-nowrap{flex-wrap:nowrap}.md\:px-6{padding-inline:calc(var(--spacing) * 6)}.md\:py-0{padding-block:0}}@media (width>=64rem){.lg\:min-h-0{min-height:0}.lg\:grid-cols-\[minmax\(0\,1fr\)_416px\]{grid-template-columns:minmax(0,1fr) 416px}.lg\:gap-4{gap:calc(var(--spacing) * 4)}.lg\:overflow-hidden{overflow:hidden}.lg\:overflow-y-auto{overflow-y:auto}.lg\:p-4{padding:calc(var(--spacing) * 4)}}@media (width>=80rem){.xl\:inline{display:inline}}@media (width>=96rem){.\32 xl\:block{display:block}}}:root{--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light;--accent:var(--color-classify);--accent-soft:var(--color-classify-soft)}[data-line=segment]{--accent:var(--color-segment);--accent-soft:var(--color-segment-soft)}html,body,#root{height:100%}body{background:radial-gradient(60rem 40rem at -10% -10%, oklch(93% .05 262/.9), transparent 60%), radial-gradient(50rem 36rem at 110% 0%, oklch(94% .05 340/.8), transparent 60%), radial-gradient(50rem 40rem at 50% 120%, oklch(95% .06 90/.8), transparent 60%), var(--color-ground);color:var(--color-ink);font-family:var(--font-sans);-webkit-font-smoothing:antialiased;background-attachment:fixed;margin:0;font-size:18px;line-height:1.5}button,[role=button]{cursor:pointer}h1,h2,h3,.display{font-family:var(--font-display);letter-spacing:-.01em}.press{transition:transform .18s var(--ease-spring)}.press:active{transform:scale(.96)}@keyframes pop-in{0%{opacity:0;transform:scale(.85)}to{opacity:1;transform:scale(1)}}.pop-in{animation:pop-in .38s var(--ease-spring)}@keyframes wobble{0%,to{transform:rotate(0)}25%{transform:rotate(-8deg)}75%{transform:rotate(8deg)}}.wobble{animation:.5s ease-in-out wobble}:focus-visible{outline:3px solid var(--accent);outline-offset:2px}.num{font-variant-numeric:tabular-nums}.card{background:var(--color-surface);border-radius:var(--radius-card);box-shadow:var(--shadow-card);border:1px solid oklch(20% .02 280/.07)}.checker{background-color:oklch(93% .003 260);background-image:linear-gradient(45deg,oklch(90% .003 260) 25%,#0000 25%),linear-gradient(-45deg,oklch(90% .003 260) 25%,#0000 25%),linear-gradient(45deg,#0000 75%,oklch(90% .003 260) 75%),linear-gradient(-45deg,#0000 75%,oklch(90% .003 260) 75%);background-position:0 0,0 10px,10px -10px,-10px 0;background-size:20px 20px}input[type=range].slider{appearance:none;background:0 0;width:100%;height:28px}input[type=range].slider::-webkit-slider-runnable-track{background:linear-gradient(to right, var(--track) var(--fill), var(--color-rule-strong) var(--fill));border-radius:99px;height:6px}input[type=range].slider::-moz-range-track{background:linear-gradient(to right, var(--track) var(--fill), var(--color-rule-strong) var(--fill));border-radius:99px;height:6px}input[type=range].slider::-webkit-slider-thumb{-webkit-appearance:none;border:2px solid var(--track);background:#fff;border-radius:50%;width:22px;height:22px;margin-top:-8px;box-shadow:0 1px 4px oklch(20% .01 260/.25)}input[type=range].slider::-moz-range-thumb{border:2px solid var(--track);background:#fff;border-radius:50%;width:18px;height:18px}@keyframes pulse-bar{0%{transform:translate(-100%)}to{transform:translate(250%)}}.busy-bar{animation:pulse-bar 1.1s var(--ease-out) infinite}@media (prefers-reduced-motion:reduce){*,:before,:after{transition-duration:0s!important;animation-duration:0s!important}}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-gradient-position{syntax:"*";inherits:false}@property --tw-gradient-from{syntax:"<color>";inherits:false;initial-value:#0000}@property --tw-gradient-via{syntax:"<color>";inherits:false;initial-value:#0000}@property --tw-gradient-to{syntax:"<color>";inherits:false;initial-value:#0000}@property --tw-gradient-stops{syntax:"*";inherits:false}@property --tw-gradient-via-stops{syntax:"*";inherits:false}@property --tw-gradient-from-position{syntax:"<length-percentage>";inherits:false;initial-value:0%}@property --tw-gradient-via-position{syntax:"<length-percentage>";inherits:false;initial-value:50%}@property --tw-gradient-to-position{syntax:"<length-percentage>";inherits:false;initial-value:100%}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@keyframes pulse{50%{opacity:.5}}
static/index.html ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>Image Preprocessing Lab</title>
7
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ccircle cx='16' cy='16' r='15' fill='%23da291c'/%3E%3Ccircle cx='16' cy='16' r='7' fill='%23fff'/%3E%3C/svg%3E" />
8
+ <script type="module" crossorigin src="/assets/index-3TAydZ6P.js"></script>
9
+ <link rel="stylesheet" crossorigin href="/assets/index-BRWcS88i.css">
10
+ </head>
11
+ <body>
12
+ <div id="root"></div>
13
+ </body>
14
+ </html>
weights/torch/hub/checkpoints/resnet50-0676ba61.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0676ba61b6795bbe1773cffd859882e5e297624d384b6993f7c9e683e722fb8a
3
+ size 102530333
weights/yolo11s-seg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1caa81c0195412efa411b632bcfb8c184939dddb6ae41f6a80c41b211ff257c3
3
+ size 20669228