File size: 12,381 Bytes
eecf956
 
 
 
 
 
 
 
 
 
 
4db7551
 
 
 
 
eecf956
4db7551
 
 
 
eecf956
 
4db7551
eecf956
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4db7551
eecf956
 
 
8d82fea
 
eecf956
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4db7551
eecf956
 
 
 
 
 
 
 
 
 
 
 
 
4db7551
eecf956
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d82fea
eecf956
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de17047
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import gradio as gr
import pandas as pd
import requests
import os
import csv
from io import BytesIO
from PIL import Image
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
from filelock import FileLock 

if os.path.exists("/data"):
    DATA_DIR = "/data"
else:
    DATA_DIR = "."

URL_FILE = "urls.txt"
LABEL_FILE = os.path.join(DATA_DIR, "annotations.csv")
VERIFY_FILE = os.path.join(DATA_DIR, "verifications.csv")
SKIP_FILE = os.path.join(DATA_DIR, "skipped.csv")
LOCK_FILE = os.path.join(DATA_DIR, "data.lock")

MAX_IMAGES = 6
THUMB_SIZE = (350, 350)
ROOM_CLASSES = ["living_room", "bedroom", "kitchen", "bathroom", "dining_room", "outdoor", "other"]

def init_files():
    for f in [LABEL_FILE, VERIFY_FILE, SKIP_FILE]:
        if not os.path.exists(f):
            if f == LABEL_FILE: cols = ["timestamp", "user", "group_id", "url", "score", "label"]
            elif f == VERIFY_FILE: cols = ["timestamp", "user", "group_id", "url", "is_correct", "corrected_label"]
            else: cols = ["timestamp", "user", "group_id"]
            pd.DataFrame(columns=cols).to_csv(f, index=False)
    if not os.path.exists(URL_FILE):
        with open(URL_FILE, "w") as f: f.write("")

init_files()

def get_image_optimized(url):
    if not url: return None
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
        response = requests.get(url, headers=headers, timeout=3)
        if response.status_code == 200:
            img = Image.open(BytesIO(response.content))
            img.thumbnail(THUMB_SIZE, Image.Resampling.LANCZOS)
            return img
    except:
        pass
    
    return url 

def get_ordered_groups():
    groups = []
    seen = set()
    if not os.path.exists(URL_FILE): return []
    with open(URL_FILE, 'r') as f:
        for line in f:
            u = line.strip()
            if u:
                try: gid = u.split("-m")[0].split("/")[-1]
                except: gid = "unknown"
                if gid not in seen:
                    groups.append(gid)
                    seen.add(gid)
    return groups

def get_group_urls(target_gid):
    urls = []
    with open(URL_FILE, 'r') as f:
        for line in f:
            u = line.strip()
            if u and target_gid in u:
                urls.append(u)
    return urls[:MAX_IMAGES]

def get_saved_values(gid, mode):
    saved_data = {}
    try:
        filename = LABEL_FILE if mode == "label" else VERIFY_FILE
        if os.path.exists(filename):
            df = pd.read_csv(filename)
            rows = df[df['group_id'] == gid]
            for _, row in rows.iterrows():
                if mode == "label":
                    saved_data[row['url']] = {"score": row['score'], "label": row['label']}
                else:
                    saved_data[row['url']] = {"is_correct": row['is_correct'], "label": row['corrected_label']}
    except: pass
    return saved_data

def get_stats_text():
    all_gids = get_ordered_groups()
    try: l = len(pd.read_csv(LABEL_FILE)['group_id'].unique())
    except: l = 0
    return f"**Total Properties:** {len(all_gids)} | **Labeled:** {l}"

def render_workspace(mode, history, specific_index=None, move_back=False):
    all_groups = get_ordered_groups()
    total_groups = len(all_groups)
    
    try: l_done = set(pd.read_csv(LABEL_FILE)['group_id'].unique())
    except: l_done = set()
    try: v_done = set(pd.read_csv(VERIFY_FILE)['group_id'].unique())
    except: v_done = set()
    try: s_done = set(pd.read_csv(SKIP_FILE)['group_id'].unique())
    except: s_done = set()

    target_gid = None
    target_idx = -1

    if specific_index is not None:
        if 0 <= specific_index < total_groups:
            target_gid = all_groups[specific_index]
            target_idx = specific_index
        else:
            return {log_box: "End of list."}

    elif move_back and len(history) > 1:
        history.pop()
        target_gid = history[-1]
        try: target_idx = all_groups.index(target_gid)
        except: target_idx = 0
        
    else:
        found = False
        for i, gid in enumerate(all_groups):
            if gid in s_done: continue
            is_ready = False
            if mode == "label" and gid not in l_done: is_ready = True
            elif mode == "verify" and gid in l_done and gid not in v_done: is_ready = True
            
            if is_ready:
                target_gid = gid
                target_idx = i
                found = True
                break
        
        if not found:
             return {screen_menu: gr.update(visible=True), screen_work: gr.update(visible=False), log_box: "No more tasks found."}

    urls = get_group_urls(target_gid)
    
    if not history or history[-1] != target_gid:
        history.append(target_gid)
        
    saved_vals = get_saved_values(target_gid, mode)
    r1_vals = get_saved_values(target_gid, "label") if mode == "verify" else {}

    processed_images = [None] * MAX_IMAGES
    with ThreadPoolExecutor(max_workers=MAX_IMAGES) as executor:
        futures = {executor.submit(get_image_optimized, u): i for i, u in enumerate(urls)}
        for future in futures:
            processed_images[futures[future]] = future.result()

    header = f"# Property #{target_idx + 1} <span style='font-size:14px;color:gray;'>(ID: {target_gid})</span>"
    
    updates = {
        screen_menu: gr.update(visible=False),
        screen_work: gr.update(visible=True),
        header_md: header,
        state_urls: urls,
        state_hist: history,
        state_idx: target_idx,
        top_stats: get_stats_text(),
        log_box: f"Loaded group {target_gid}"
    }

    for i in range(MAX_IMAGES):
        img_c = img_objs[i]
        base = i * 4
        c_sld, c_drp, c_chk, c_lbl = input_objs[base], input_objs[base+1], input_objs[base+2], input_objs[base+3]
        
        if i < len(urls):
            u = urls[i]
            img_data = processed_images[i]
            
            updates[img_c] = gr.update(value=img_data, visible=True)
            
            v_sc = saved_vals.get(u, {}).get('score', 5)
            v_lbl = saved_vals.get(u, {}).get('label', ROOM_CLASSES[0])
            v_chk = saved_vals.get(u, {}).get('is_correct', True)
            
            if mode == "label":
                updates[c_sld] = gr.update(visible=True, value=v_sc)
                updates[c_drp] = gr.update(visible=True, value=v_lbl)
                updates[c_chk] = gr.update(visible=False)
                updates[c_lbl] = gr.update(visible=False)
            else:
                prev = r1_vals.get(u, {}).get('label', "Unknown")
                updates[c_sld] = gr.update(visible=False)
                updates[c_lbl] = gr.update(visible=True, value=f"**Labeled:** {prev}")
                updates[c_drp] = gr.update(visible=True, value=v_lbl)
                updates[c_chk] = gr.update(visible=True, value=v_chk)
        else:
            updates[img_c] = gr.update(value=None, visible=False)
            updates[c_sld] = gr.update(visible=False)
            updates[c_drp] = gr.update(visible=False)
            updates[c_chk] = gr.update(visible=False)
            updates[c_lbl] = gr.update(visible=False)

    return updates

def save_data(mode, history, urls, *args):
    if not history: return
    gid = history[-1]
    ts = datetime.now().isoformat()
    rows = []
    
    for i, u in enumerate(urls):
        base = i * 4
        sc, lbl, chk = args[base], args[base+1], args[base+2]
        if mode == "label": rows.append([ts, "user", gid, u, sc, lbl])
        else: rows.append([ts, "user", gid, u, chk, lbl])
        
    fname = LABEL_FILE if mode == "label" else VERIFY_FILE
    
    with FileLock(LOCK_FILE):
        with open(fname, "a", newline="") as f:
            csv.writer(f).writerows(rows)
            
    return render_workspace(mode, history)

def skip_group(idx, history, mode):
    if history:
        gid = history[-1]
        with FileLock(LOCK_FILE):
            with open(SKIP_FILE, "a", newline="") as f:
                csv.writer(f).writerow([datetime.now().isoformat(), "user", gid])
    
    return render_workspace(mode, history, specific_index=idx + 1)

def refresh_cat():
    all_gids = get_ordered_groups()
    try: l_set = set(pd.read_csv(LABEL_FILE)['group_id'].unique())
    except: l_set = set()
    try: v_set = set(pd.read_csv(VERIFY_FILE)['group_id'].unique())
    except: v_set = set()
    
    data = []
    for i, gid in enumerate(all_gids):
        s = "⚪ Pending"
        if gid in v_set: s = "✅ Verified"
        elif gid in l_set: s = "🔵 Labeled"
        data.append([i+1, s, gid])
    return pd.DataFrame(data, columns=["#", "Status", "ID"])

with gr.Blocks(title="Fast Labeler") as demo:
    
    state_mode = gr.State("label")
    state_hist = gr.State([])
    state_urls = gr.State([])
    state_idx = gr.State(0)
    
    with gr.Row(variant="panel"):
        top_stats = gr.Markdown("Loading stats...")
        btn_home = gr.Button("🏠 Home", size="sm", scale=0)

    with gr.Tabs():
        with gr.Tab("Workspace", id=0):
            with gr.Group() as screen_menu:
                gr.Markdown("# Welcome! 👋")
                gr.Markdown("Server-side compression enabled.")
                with gr.Row():
                    b_start_l = gr.Button("Start Labeling", variant="primary")
                    b_start_v = gr.Button("Start Verification")
            
            with gr.Group(visible=False) as screen_work:
                header_md = gr.Markdown()
                img_objs, input_objs = [], []
                
                with gr.Row():
                    for i in range(MAX_IMAGES):
                        with gr.Column(min_width=250):
                            img = gr.Image(interactive=False, height=280, show_label=False)
                            with gr.Group():
                                sld = gr.Slider(1, 10, step=1, label="Score", visible=False)
                                lbl = gr.Markdown(visible=False)
                                drp = gr.Dropdown(ROOM_CLASSES, label="Class", visible=False)
                                chk = gr.Checkbox(label="Correct?", value=True, visible=False)
                            img_objs.append(img)
                            input_objs.extend([sld, drp, chk, lbl])

                with gr.Row():
                    b_back = gr.Button("⬅ Back")
                    b_skip = gr.Button("Skip ➡")
                    b_save = gr.Button("💾 Save & Next", variant="primary")
                log_box = gr.Textbox(label="Log", interactive=False, max_lines=1)

        with gr.Tab("Catalog", id=1):
            with gr.Row():
                num_in = gr.Number(value=1, label="Property #", precision=0)
                b_go_l = gr.Button("Go (Label)")
                b_go_v = gr.Button("Go (Verify)")
            df_cat = gr.Dataframe(interactive=False)
            b_ref_cat = gr.Button("Refresh")

    ALL_IO = [screen_menu, screen_work, header_md, state_urls, state_hist, state_idx, top_stats, log_box] + img_objs + input_objs
    
    b_start_l.click(lambda: "label", None, state_mode).then(render_workspace, [state_mode, state_hist], ALL_IO)
    b_start_v.click(lambda: "verify", None, state_mode).then(render_workspace, [state_mode, state_hist], ALL_IO)
    
    b_save.click(save_data, [state_mode, state_hist, state_urls] + input_objs, ALL_IO)
    b_skip.click(skip_group, [state_idx, state_hist, state_mode], ALL_IO)
    b_back.click(lambda m, h: render_workspace(m, h, move_back=True), [state_mode, state_hist], ALL_IO)
    
    btn_home.click(lambda: {screen_menu: gr.update(visible=True), screen_work: gr.update(visible=False), state_hist: []}, None, [screen_menu, screen_work, state_hist])
    
    b_go_l.click(lambda: "label", None, state_mode).then(lambda n, m, h: render_workspace(m, h, specific_index=int(n)-1), [num_in, state_mode, state_hist], ALL_IO)
    b_go_v.click(lambda: "verify", None, state_mode).then(lambda n, m, h: render_workspace(m, h, specific_index=int(n)-1), [num_in, state_mode, state_hist], ALL_IO)

    b_ref_cat.click(refresh_cat, None, df_cat)
    demo.load(refresh_cat, None, df_cat).then(get_stats_text, None, top_stats)

demo.queue().launch(theme=gr.themes.Soft())