Spaces:
Running
Running
Upload folder using huggingface_hub
Browse files- app.py +45 -18
- index.html +22 -16
app.py
CHANGED
|
@@ -14,10 +14,19 @@ API_ROOT = "https://pixieduster-api.me-c41.workers.dev/api"
|
|
| 14 |
|
| 15 |
def _session_token():
|
| 16 |
"""Read the session minted by index.html. Empty string outside the browser."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
try:
|
| 18 |
from js import window # available under stlite/Pyodide
|
|
|
|
|
|
|
|
|
|
| 19 |
return str(window.pdSession or "")
|
| 20 |
-
except Exception:
|
| 21 |
return ""
|
| 22 |
|
| 23 |
|
|
@@ -37,8 +46,6 @@ def _friendly_error(response):
|
|
| 37 |
detail = None
|
| 38 |
if response.status_code == 429:
|
| 39 |
return detail or "The free daily limit has been reached. Try again tomorrow."
|
| 40 |
-
if response.status_code == 401:
|
| 41 |
-
return "Your session expired. Reload the page."
|
| 42 |
return detail or f"The service returned an error ({response.status_code})."
|
| 43 |
|
| 44 |
|
|
@@ -50,7 +57,7 @@ def call_gemini(api_key, model, prompt, uploaded_files=[], require_json=False):
|
|
| 50 |
url = f"{API_ROOT}/models/{model}:generateContent"
|
| 51 |
parts = [{"text": prompt}]
|
| 52 |
for file in uploaded_files:
|
| 53 |
-
mime_type = file
|
| 54 |
if mime_type.startswith("text/") or mime_type in ["application/json", "text/markdown", "text/csv"]:
|
| 55 |
text_data = file.getvalue().decode("utf-8", errors="replace")
|
| 56 |
parts.append({"text": f"\n\n--- Document: {file.name} ---\n{text_data}\n--- End Document ---\n"})
|
|
@@ -62,20 +69,30 @@ def call_gemini(api_key, model, prompt, uploaded_files=[], require_json=False):
|
|
| 62 |
payload["generationConfig"] = {
|
| 63 |
"responseMimeType": "application/json",
|
| 64 |
"responseSchema": {
|
| 65 |
-
"type": "
|
| 66 |
-
"
|
| 67 |
-
"
|
| 68 |
-
|
| 69 |
-
"
|
| 70 |
-
|
| 71 |
-
"
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
}
|
| 74 |
-
}
|
| 75 |
-
|
| 76 |
-
|
| 77 |
}
|
| 78 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
response = requests.post(url, headers=_api_headers(), json=payload)
|
| 80 |
if not response.ok:
|
| 81 |
raise Exception(_friendly_error(response))
|
|
@@ -428,8 +445,18 @@ if st.session_state.step == 1:
|
|
| 428 |
with st.status("Running Analysis...", expanded=True) as status:
|
| 429 |
try:
|
| 430 |
st.markdown("<i class='fa-solid fa-magnifying-glass fa-beat-fade' style='color:#ffd700;'></i> Inspecting your writing samples...", unsafe_allow_html=True)
|
| 431 |
-
#
|
| 432 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 433 |
|
| 434 |
st.markdown("<i class='fa-solid fa-list-check fa-flip' style='color:#ffd700;'></i> Formulating profiling questions...", unsafe_allow_html=True)
|
| 435 |
prompt_instruction = (
|
|
@@ -441,7 +468,7 @@ if st.session_state.step == 1:
|
|
| 441 |
|
| 442 |
time.sleep(0.1) # Force UI to render before blocking network request
|
| 443 |
|
| 444 |
-
response_text = call_gemini(api_key, model_id, prompt_instruction,
|
| 445 |
clean_text = response_text.strip()
|
| 446 |
if clean_text.startswith("```json"): clean_text = clean_text[7:]
|
| 447 |
elif clean_text.startswith("```"): clean_text = clean_text[3:]
|
|
|
|
| 14 |
|
| 15 |
def _session_token():
|
| 16 |
"""Read the session minted by index.html. Empty string outside the browser."""
|
| 17 |
+
try:
|
| 18 |
+
import session_token
|
| 19 |
+
return session_token.TOKEN
|
| 20 |
+
except ImportError:
|
| 21 |
+
pass
|
| 22 |
+
|
| 23 |
try:
|
| 24 |
from js import window # available under stlite/Pyodide
|
| 25 |
+
token = str(window.localStorage.getItem("pdSession") or "")
|
| 26 |
+
if token:
|
| 27 |
+
return token
|
| 28 |
return str(window.pdSession or "")
|
| 29 |
+
except Exception as e:
|
| 30 |
return ""
|
| 31 |
|
| 32 |
|
|
|
|
| 46 |
detail = None
|
| 47 |
if response.status_code == 429:
|
| 48 |
return detail or "The free daily limit has been reached. Try again tomorrow."
|
|
|
|
|
|
|
| 49 |
return detail or f"The service returned an error ({response.status_code})."
|
| 50 |
|
| 51 |
|
|
|
|
| 57 |
url = f"{API_ROOT}/models/{model}:generateContent"
|
| 58 |
parts = [{"text": prompt}]
|
| 59 |
for file in uploaded_files:
|
| 60 |
+
mime_type = getattr(file, "type", "") or "application/octet-stream"
|
| 61 |
if mime_type.startswith("text/") or mime_type in ["application/json", "text/markdown", "text/csv"]:
|
| 62 |
text_data = file.getvalue().decode("utf-8", errors="replace")
|
| 63 |
parts.append({"text": f"\n\n--- Document: {file.name} ---\n{text_data}\n--- End Document ---\n"})
|
|
|
|
| 69 |
payload["generationConfig"] = {
|
| 70 |
"responseMimeType": "application/json",
|
| 71 |
"responseSchema": {
|
| 72 |
+
"type": "OBJECT",
|
| 73 |
+
"properties": {
|
| 74 |
+
"questions": {
|
| 75 |
+
"type": "ARRAY",
|
| 76 |
+
"items": {
|
| 77 |
+
"type": "OBJECT",
|
| 78 |
+
"properties": {
|
| 79 |
+
"question": {"type": "STRING"},
|
| 80 |
+
"options": {
|
| 81 |
+
"type": "ARRAY",
|
| 82 |
+
"items": {"type": "STRING"}
|
| 83 |
+
}
|
| 84 |
+
},
|
| 85 |
+
"required": ["question", "options"]
|
| 86 |
}
|
| 87 |
+
}
|
| 88 |
+
},
|
| 89 |
+
"required": ["questions"]
|
| 90 |
}
|
| 91 |
}
|
| 92 |
+
token = _session_token()
|
| 93 |
+
if token.startswith("ERROR:"):
|
| 94 |
+
raise Exception(f"Session Token Debug: {token}")
|
| 95 |
+
|
| 96 |
response = requests.post(url, headers=_api_headers(), json=payload)
|
| 97 |
if not response.ok:
|
| 98 |
raise Exception(_friendly_error(response))
|
|
|
|
| 445 |
with st.status("Running Analysis...", expanded=True) as status:
|
| 446 |
try:
|
| 447 |
st.markdown("<i class='fa-solid fa-magnifying-glass fa-beat-fade' style='color:#ffd700;'></i> Inspecting your writing samples...", unsafe_allow_html=True)
|
| 448 |
+
# Convert UploadedFile objects to in-memory objects immediately
|
| 449 |
+
# so they survive when the file_uploader widget is unmounted in Step 2.
|
| 450 |
+
class MemFile:
|
| 451 |
+
def __init__(self, name, type, data):
|
| 452 |
+
self.name = name
|
| 453 |
+
self.type = type
|
| 454 |
+
self.data = data
|
| 455 |
+
def getvalue(self):
|
| 456 |
+
return self.data
|
| 457 |
+
|
| 458 |
+
mem_files = [MemFile(f.name, f.type, f.getvalue()) for f in uploaded_files]
|
| 459 |
+
st.session_state.uploaded_genai_files = mem_files
|
| 460 |
|
| 461 |
st.markdown("<i class='fa-solid fa-list-check fa-flip' style='color:#ffd700;'></i> Formulating profiling questions...", unsafe_allow_html=True)
|
| 462 |
prompt_instruction = (
|
|
|
|
| 468 |
|
| 469 |
time.sleep(0.1) # Force UI to render before blocking network request
|
| 470 |
|
| 471 |
+
response_text = call_gemini(api_key, model_id, prompt_instruction, mem_files, require_json=True)
|
| 472 |
clean_text = response_text.strip()
|
| 473 |
if clean_text.startswith("```json"): clean_text = clean_text[7:]
|
| 474 |
elif clean_text.startswith("```"): clean_text = clean_text[3:]
|
index.html
CHANGED
|
@@ -11,7 +11,7 @@
|
|
| 11 |
<!-- Turnstile: proves the visitor is a person, so the hosted key can be
|
| 12 |
used without anyone typing a key of their own. The sitekey is public
|
| 13 |
by design; the matching secret lives only on the Worker. -->
|
| 14 |
-
<script
|
| 15 |
<style>
|
| 16 |
html, body { margin: 0; background: #0f081c; }
|
| 17 |
/* Normal flow, pinned to the top. `position: fixed` centerd this in the
|
|
@@ -102,6 +102,26 @@
|
|
| 102 |
});
|
| 103 |
if (!r.ok) throw new Error(await r.text());
|
| 104 |
window.pdSession = (await r.json()).session;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
pdReady();
|
| 106 |
} catch (e) {
|
| 107 |
status.textContent =
|
|
@@ -133,21 +153,7 @@
|
|
| 133 |
},
|
| 134 |
});
|
| 135 |
};
|
| 136 |
-
stlite.mount(
|
| 137 |
-
{
|
| 138 |
-
requirements: ["requests"], // dotenv went with the API key form
|
| 139 |
-
entrypoint: "app.py",
|
| 140 |
-
files: {
|
| 141 |
-
"app.py": {
|
| 142 |
-
url: "./app.py",
|
| 143 |
-
},
|
| 144 |
-
"logo.png": {
|
| 145 |
-
url: "./logo.png",
|
| 146 |
-
}
|
| 147 |
-
},
|
| 148 |
-
},
|
| 149 |
-
document.getElementById("root")
|
| 150 |
-
);
|
| 151 |
</script>
|
|
|
|
| 152 |
</body>
|
| 153 |
</html>
|
|
|
|
| 11 |
<!-- Turnstile: proves the visitor is a person, so the hosted key can be
|
| 12 |
used without anyone typing a key of their own. The sitekey is public
|
| 13 |
by design; the matching secret lives only on the Worker. -->
|
| 14 |
+
<!-- Turnstile script moved to body to prevent race condition -->
|
| 15 |
<style>
|
| 16 |
html, body { margin: 0; background: #0f081c; }
|
| 17 |
/* Normal flow, pinned to the top. `position: fixed` centerd this in the
|
|
|
|
| 102 |
});
|
| 103 |
if (!r.ok) throw new Error(await r.text());
|
| 104 |
window.pdSession = (await r.json()).session;
|
| 105 |
+
window.localStorage.setItem("pdSession", window.pdSession);
|
| 106 |
+
|
| 107 |
+
// Mount stlite ONLY AFTER we have the session token, and pass it directly as a Python module!
|
| 108 |
+
stlite.mount(
|
| 109 |
+
{
|
| 110 |
+
requirements: ["requests"],
|
| 111 |
+
entrypoint: "app.py",
|
| 112 |
+
files: {
|
| 113 |
+
"app.py": {
|
| 114 |
+
url: "./app.py?v=" + Date.now(),
|
| 115 |
+
},
|
| 116 |
+
"logo.png": {
|
| 117 |
+
url: "./logo.png",
|
| 118 |
+
},
|
| 119 |
+
"session_token.py": "TOKEN = '" + window.pdSession + "'\n"
|
| 120 |
+
},
|
| 121 |
+
},
|
| 122 |
+
document.getElementById("root")
|
| 123 |
+
);
|
| 124 |
+
|
| 125 |
pdReady();
|
| 126 |
} catch (e) {
|
| 127 |
status.textContent =
|
|
|
|
| 153 |
},
|
| 154 |
});
|
| 155 |
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
</script>
|
| 157 |
+
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js?onload=onloadTurnstileCallback&render=explicit" async defer></script>
|
| 158 |
</body>
|
| 159 |
</html>
|