Theflame47 commited on
Commit
b615c89
·
verified ·
1 Parent(s): e8332fd

Create ui.py

Browse files
Files changed (1) hide show
  1. ui.py +188 -0
ui.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ui.py
2
+ import html, threading
3
+ from typing import Any, Dict, List
4
+ from fastapi import APIRouter, HTTPException
5
+ from fastapi.responses import HTMLResponse, JSONResponse
6
+
7
+ from data import (
8
+ get_pages, get_state, ensure_page_loaded, build_all_pages, is_complete,
9
+ model_id, license_label_and_url
10
+ )
11
+
12
+ router = APIRouter()
13
+
14
+ def _render_table(models: List[Dict[str, Any]]) -> str:
15
+ rows = []
16
+ for m in models:
17
+ mid = html.escape(model_id(m))
18
+ desc = html.escape((m.get("description") or "")[:200])
19
+ thumb = m.get("cover_image_url") or m.get("cover_image") or ""
20
+ vis = html.escape(m.get("visibility") or "")
21
+ tags = m.get("tags") or m.get("categories") or []
22
+ tags_html = " ".join(f"<span class='tag'>{html.escape(str(t))}</span>" for t in tags[:8])
23
+
24
+ lic_label, lic_url = license_label_and_url(m)
25
+ lic_label_h = html.escape(lic_label)
26
+ lic_html = f"<a href='{html.escape(lic_url)}' target='_blank' rel='noopener'>{lic_label_h}</a>" if lic_url else lic_label_h
27
+
28
+ src_links = []
29
+ if m.get("github_url"):
30
+ src_links.append(f"<a href='{html.escape(m['github_url'])}' target='_blank' rel='noopener'>GitHub</a>")
31
+ if m.get("paper_url"):
32
+ src_links.append(f"<a href='{html.escape(m['paper_url'])}' target='_blank' rel='noopener'>Paper</a>")
33
+ if lic_url:
34
+ src_links.append(f"<a href='{html.escape(lic_url)}' target='_blank' rel='noopener'>License</a>")
35
+ sources_html = " | ".join(src_links)
36
+
37
+ run_ct = m.get("run_count")
38
+ run_html = f"<span class='pill'>{run_ct:,} runs</span>" if isinstance(run_ct, int) else ""
39
+
40
+ thumb_html = f"<img src='{html.escape(thumb)}' alt='' />" if thumb else ""
41
+ rows.append(
42
+ f"<tr>"
43
+ f"<td class='thumb'>{thumb_html}</td>"
44
+ f"<td class='id'>{mid}<br>{run_html}</td>"
45
+ f"<td class='desc'>{desc}</td>"
46
+ f"<td class='vis'>{vis}</td>"
47
+ f"<td class='lic'>{lic_html}</td>"
48
+ f"<td class='src'>{sources_html}</td>"
49
+ f"<td class='tags'>{tags_html}</td>"
50
+ f"</tr>"
51
+ )
52
+ return (
53
+ "<table class='grid'>"
54
+ "<thead><tr>"
55
+ "<th>Thumbnail</th><th>ID / Runs</th><th>Description</th><th>Visibility</th>"
56
+ "<th>License</th><th>Sources</th><th>Tags</th>"
57
+ "</tr></thead><tbody>"
58
+ + "\n".join(rows) +
59
+ "</tbody></table>"
60
+ )
61
+
62
+ def _render_pagination(current_page: int) -> str:
63
+ pages = len(get_pages())
64
+ links = []
65
+ for i in range(1, pages + 1):
66
+ if i == current_page:
67
+ links.append(f"<span class='page current'>{i}</span>")
68
+ else:
69
+ links.append(f"<a class='page' href='/page/{i}'>{i}</a>")
70
+ # “Load next” hint if more exist
71
+ state = get_state()
72
+ if state["more"]:
73
+ links.append(f"<a class='page next' href='/page/{pages + 1}'>Load {pages + 1}</a>")
74
+ return "<div class='pagination'>" + " ".join(links) + "</div>"
75
+
76
+ def _shell(page_index_0: int, html_table: str, *, search_query: str = "") -> str:
77
+ page_num = page_index_0 + 1
78
+ state = get_state()
79
+ search_disabled = "" if state["complete"] else "disabled"
80
+ search_opacity = "1.0" if state["complete"] else "0.45"
81
+ import html as _h
82
+ return f"""
83
+ <!doctype html>
84
+ <html><head><meta charset="utf-8" />
85
+ <title>Replicate Catalog — Page {page_num}</title>
86
+ <style>
87
+ body {{ font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial; margin: 24px; }}
88
+ .meta {{ margin-bottom: 12px; color: #444; display:flex; gap:16px; align-items:center; flex-wrap:wrap; }}
89
+ .grid {{ width:100%; border-collapse: collapse; }}
90
+ .grid th, .grid td {{ border-bottom:1px solid #eee; padding:10px; vertical-align:top; }}
91
+ .grid th {{ text-align:left; background:#fafafa; }}
92
+ .thumb img {{ width:72px; height:72px; object-fit:cover; border-radius:8px; }}
93
+ .id {{ font-weight:600; white-space:nowrap; }}
94
+ .desc {{ color:#333; max-width:700px; }}
95
+ .vis {{ white-space:nowrap; color:#555; }}
96
+ .lic {{ white-space:nowrap; }}
97
+ .src {{ font-size:13px; color:#0366d6; }}
98
+ .tags .tag {{ display:inline-block; padding:2px 8px; margin:2px; background:#f2f2f7; border:1px solid #e5e5ea; border-radius:999px; font-size:12px; color:#333; }}
99
+ .pagination {{ margin-top:20px; }}
100
+ .page {{ display:inline-block; padding:6px 10px; margin-right:6px; border:1px solid #ddd; border-radius:6px; text-decoration:none; color:#333; }}
101
+ .page.current {{ background:#111; color:#fff; border-color:#111; cursor:default; }}
102
+ .page.next {{ font-weight:600; }}
103
+ .searchbar {{ display:flex; gap:8px; align-items:center; }}
104
+ .searchbar input[type="text"] {{ width:360px; padding:8px 10px; border:1px solid #ddd; border-radius:8px; opacity:{search_opacity}; }}
105
+ .searchbar button {{ padding:8px 12px; border:1px solid #111; background:#111; color:#fff; border-radius:8px; opacity:{search_opacity}; }}
106
+ .pill {{ display:inline-block; padding:2px 8px; border:1px solid #ddd; border-radius:999px; font-size:12px; color:#333; }}
107
+ </style></head>
108
+ <body>
109
+ <div class="meta">
110
+ <strong>Replicate catalog</strong>
111
+ <span class="pill">page {page_num} of {state['pages']} known</span>
112
+ <span class="pill">more pages available: {"yes" if state["more"] else "no"}</span>
113
+ <span class="pill">building: {"yes" if state["building"] else "no"}</span>
114
+ <span class="pill">complete: {"yes" if state["complete"] else "no"}</span>
115
+ </div>
116
+ <form class="searchbar" method="GET" action="/search" onsubmit="return onSearchSubmit();" >
117
+ <input id="q" name="q" type="text" placeholder="Search models, descriptions, tags" value="{_h.escape(search_query)}" {search_disabled} />
118
+ <button id="qbtn" type="submit" {search_disabled}>Search</button>
119
+ <span id="searchHint" style="color:#666; font-size:12px;">{'' if state["complete"] else 'Search available after catalog completes.'}</span>
120
+ </form>
121
+ {html_table}
122
+ {_render_pagination(page_num)}
123
+ <script>
124
+ document.addEventListener("DOMContentLoaded", function() {{
125
+ fetch("/build_all", {{ method: "POST" }}).catch(()=>{});
126
+ const poll = () => {{
127
+ fetch("/status").then(r=>r.json()).then(s => {{
128
+ if (s.complete) {{
129
+ const q = document.getElementById("q");
130
+ const b = document.getElementById("qbtn");
131
+ const hint = document.getElementById("searchHint");
132
+ if (q && b) {{
133
+ q.disabled = false; b.disabled = false;
134
+ q.style.opacity = "1.0"; b.style.opacity = "1.0";
135
+ if (hint) hint.textContent = "";
136
+ }}
137
+ }}
138
+ document.title = "Replicate Catalog — Page {page_num} (" + s.pages + " known)";
139
+ if (!s.complete) setTimeout(poll, 1200);
140
+ }}).catch(()=>setTimeout(poll, 2000));
141
+ }};
142
+ poll();
143
+ }});
144
+ function onSearchSubmit() {{
145
+ const q = document.getElementById("q");
146
+ return q && !q.disabled;
147
+ }}
148
+ </script>
149
+ </body></html>
150
+ """
151
+
152
+ @router.get("/page/{n}", response_class=HTMLResponse)
153
+ def page(n: int):
154
+ if n < 1:
155
+ raise HTTPException(status_code=400, detail="Page must be >= 1")
156
+ idx = n - 1
157
+ ensure_page_loaded(idx)
158
+ pages = get_pages()
159
+ if idx >= len(pages):
160
+ raise HTTPException(status_code=404, detail="No more pages.")
161
+ models = pages[idx]["results"]
162
+ return HTMLResponse(_shell(idx, _render_table(models)))
163
+
164
+ @router.post("/build_all")
165
+ def build_all():
166
+ import threading as _t
167
+ from data import is_complete as _done
168
+ if _done():
169
+ return JSONResponse({"started": False, "reason": "complete"}, status_code=200)
170
+ _t.Thread(target=build_all_pages, daemon=True).start()
171
+ return JSONResponse({"started": True}, status_code=202)
172
+
173
+ @router.get("/status")
174
+ def status():
175
+ return JSONResponse(get_state())
176
+
177
+ @router.get("/search", response_class=HTMLResponse)
178
+ def search(q: str = ""):
179
+ from data import search_models, flatten_models
180
+ idx = 0
181
+ base = flatten_models()[: get_pages()[0]["results"].__len__()] if get_pages() else []
182
+ if is_complete() and q.strip():
183
+ results = search_models(q)
184
+ content = _render_table(results)
185
+ return HTMLResponse(_shell(idx, content, search_query=q))
186
+ else:
187
+ content = _render_table(base)
188
+ return HTMLResponse(_shell(idx, content, search_query=q))