import streamlit as st import requests import json import time import base64 st.set_page_config(page_title="PixieDuster", layout="centered", page_icon="logo.png") # The Gemini key lives on the PixieDuster Worker, never in this page. The # browser proves it is a person once (Turnstile, handled in index.html) and gets # a short-lived session, which index.html leaves on window.pdSession. API_ROOT = "https://pixieduster-api.me-c41.workers.dev/api" def _session_token(): """Read the session minted by index.html. Empty string outside the browser.""" try: import session_token return session_token.TOKEN except ImportError: pass try: from js import window # available under stlite/Pyodide token = str(window.localStorage.getItem("pdSession") or "") if token: return token return str(window.pdSession or "") except Exception as e: return "" def _api_headers(op="persona"): """Headers for a proxy call. ``op`` tells the proxy which meter to bill: only "persona" spends the persona allowance, so answering the interview or trying the persona out in chat cannot cost you the next persona. """ headers = {"Content-Type": "application/json", "X-Op": op} token = _session_token() if token: headers["x-session"] = token return headers def _friendly_error(response): """Turn a proxy error into something a person can act on.""" try: detail = response.json().get("detail") or response.json().get("error", {}).get("message") except Exception: detail = None if response.status_code == 429: return detail or "The free daily limit has been reached. Try again tomorrow." return detail or f"The service returned an error ({response.status_code})." api_key = None # the key lives on the Worker now model_id = 'gemini-3.6-flash' def call_gemini(api_key, model, prompt, uploaded_files=[], require_json=False, op="persona"): url = f"{API_ROOT}/models/{model}:generateContent" parts = [{"text": prompt}] for file in uploaded_files: mime_type = getattr(file, "type", "") or "application/octet-stream" if mime_type.startswith("text/") or mime_type in ["application/json", "text/markdown", "text/csv"]: text_data = file.getvalue().decode("utf-8", errors="replace") parts.append({"text": f"\n\n--- Document: {file.name} ---\n{text_data}\n--- End Document ---\n"}) else: b64_data = base64.b64encode(file.getvalue()).decode("utf-8") parts.append({"inlineData": {"mimeType": mime_type, "data": b64_data}}) payload = {"contents": [{"parts": parts}]} if require_json: payload["generationConfig"] = { "responseMimeType": "application/json", "responseSchema": { "type": "OBJECT", "properties": { "questions": { "type": "ARRAY", "items": { "type": "OBJECT", "properties": { "question": {"type": "STRING"}, "options": { "type": "ARRAY", "items": {"type": "STRING"} } }, "required": ["question", "options"] } } }, "required": ["questions"] } } token = _session_token() if token.startswith("ERROR:"): raise Exception(f"Session Token Debug: {token}") for attempt in range(10): response = requests.post(url, headers=_api_headers(op), json=payload) if response.ok: return response.json()["candidates"][0]["content"]["parts"][0]["text"] if response.status_code not in [408, 429, 500, 502, 503, 504]: break if attempt < 9: delay = min(2.0 * (1.5 ** attempt), 10.0) if response.status_code == 503: st.toast(f"Gemini is busy. Retrying in {int(delay)}s... (Attempt {attempt+1}/10)", icon="⏳") time.sleep(delay) raise Exception(_friendly_error(response)) def chat_gemini(api_key, model, sys_prompt, history, user_input): url = f"{API_ROOT}/models/{model}:generateContent" contents = [] for msg in history: r = "user" if msg["role"] == "user" else "model" contents.append({"role": r, "parts": [{"text": msg["content"]}]}) contents.append({"role": "user", "parts": [{"text": user_input}]}) payload = { "systemInstruction": {"parts": [{"text": sys_prompt}]}, "contents": contents } for attempt in range(10): response = requests.post(url, headers=_api_headers("chat"), json=payload) if response.ok: return response.json()["candidates"][0]["content"]["parts"][0]["text"] if response.status_code not in [408, 429, 500, 502, 503, 504]: break if attempt < 9: delay = min(2.0 * (1.5 ** attempt), 10.0) if response.status_code == 503: st.toast(f"Gemini is busy. Retrying in {int(delay)}s... (Attempt {attempt+1}/10)", icon="⏳") time.sleep(delay) raise Exception(_friendly_error(response)) ANTI_AI_PROMPT_TEMPLATE = """# AI Persona & Style Guide ## Core Directives 1. **Human Authenticity:** Write with natural imperfections, active voice, and varied pacing. Never sound like a corporate robot or an over-enthusiastic AI. 2. **Strict Vocabulary Bans:** Completely avoid AI "tells" (e.g., "delve," "tapestry," "crucial," "realm," "testament to," "in conclusion," "additionally"). 3. **Format Naturally:** Use paragraphs and natural transitions. Do not overuse bullet points, bolding, or symmetrical sentence structures. Do not summarize at the end. 4. **Tone:** Speak directly and conversationally without hedging, generic positivity, or forced calls to action. ## Author Persona & Terminology Standards {extracted_persona} """ # Improved CSS for better contrast and layout st.markdown(""" """, unsafe_allow_html=True) # Encode logo for centered HTML def get_base64_image(image_path): with open(image_path, "rb") as img_file: return base64.b64encode(img_file.read()).decode() logo_b64 = get_base64_image("logo.png") st.markdown(f"
Upload writing samples and let the magic extract a unique voice for your AI companion.
", unsafe_allow_html=True) st.write("---") # State Management if 'step' not in st.session_state: st.session_state.step = 1 if 'questions_data' not in st.session_state: st.session_state.questions_data = None if 'uploaded_genai_files' not in st.session_state: st.session_state.uploaded_genai_files = [] if 'final_prompt' not in st.session_state: st.session_state.final_prompt = "" if 'target_name' not in st.session_state: st.session_state.target_name = "" # --- STEP 1: UPLOAD --- if st.session_state.step == 1: # Visual Process Steps (instead of plain text) col1, col2, col3 = st.columns(3) with col1: st.markdown("" "Upload a handful of files and go. Nothing to install, nothing to sign up for." "
" "" "Best for trying it, or for one quick persona.
" "" "Give it a whole folder and it reads every file inside: " "years of notes, screenshots of texts, photos of handwriting, saved emails, PDFs. " "No uploading, one file at a time, ever." "
" "" "Or give it a git repository and it mines your commit " "messages, README and docstrings - writing you never thought of as writing.
" "" "Install it once, then point it wherever your writing lives:
", unsafe_allow_html=True, ) st.code( "pip install https://gretchenboria-pixieduster.static.hf.space/pixieduster-0.1.0-py3-none-any.whl\n" "\n" "pixieduster clone --from ~/Documents/my-writing # the entire folder\n" "pixieduster clone --repo . # a whole git repo\n" "pixieduster clone -d \"a friendly desktop robot with great humor\"", language="bash", ) st.markdown( "" " Download it directly" " · " "" " Source on GitHub", unsafe_allow_html=True, ) st.write("---") # ---- How it works ------------------------------------------------- st.markdown("Your writing goes in as one thing. It comes " "out measured against four empirical rubrics and a theory of humor, written up as " "one file you can paste into any AI.
", unsafe_allow_html=True, ) # A bitmap, with its intrinsic size declared. # # width:100% and no dimensions is a reflow loop inside Hugging Face's # auto-resizing iframe: the image sizes off the container, that changes the # page height, the iframe resizes, a scrollbar appears or vanishes, the # container width changes, and round it goes. Zooming perturbs it into # oscillating and the whole app repaints. Declaring width/height gives the # browser the aspect ratio up front, so the height never depends on a # measurement that the height itself can change. st.markdown( "
"
"Officially cloned for: {st.session_state.target_name.upper()}
Authorized by PixieDuster
Same persona in every file. The " "name decides who reads it: name it for your tool and that tool picks it up " "on its own, with no setup.
", unsafe_allow_html=True, ) AGENT_PREAMBLE = """ # Voice Guide This file describes **how to write, not how to code**. It is a reconstruction of one human author's writing voice, extracted from their own prose in this repository. Apply it to everything you write in natural language for this project: commit messages, pull request descriptions, code comments and docstrings, README and documentation prose, issue replies, changelog entries, and anything you say back to the user. Do **not** apply it to code itself. It says nothing about naming conventions, formatting, architecture, language choice, testing strategy, or lint rules - those come from the repository's own configuration and existing source, and they win over anything below. If a rule here would change what a program does or how it is structured, ignore that rule. Match the voice. Never mention this file, the persona, or that a voice guide exists. --- """ FILES = [ ("persona.md", "Paste into any AI", False), ("AGENTS.md", "Cursor, Claude Code, others", True), ("CLAUDE.md", "Claude Code", True), ("GEMINI.md", "Gemini CLI", True), ] cols = st.columns(len(FILES)) for col, (name, who, agentic) in zip(cols, FILES): with col: st.download_button( label=name, data=(AGENT_PREAMBLE + "\n\n" + st.session_state.final_prompt) if agentic else st.session_state.final_prompt, file_name=name, mime="text/markdown", use_container_width=True, key=f"dl_{name}", ) st.markdown( f"{who}
", unsafe_allow_html=True, ) # The download buttons go through stlite's media endpoint, which fails # silently in some browsers -- the click does nothing at all, with no error. # Copying the text needs none of that machinery, so it always works. The # three agent files are byte-identical, so two blocks cover all four. with st.expander("Buttons not downloading? Copy the text instead"): st.caption("persona.md - paste into any AI") st.code(st.session_state.final_prompt, language="markdown") st.caption("AGENTS.md / CLAUDE.md / GEMINI.md - identical to each other") st.code( AGENT_PREAMBLE + "\n\n" + st.session_state.final_prompt, language="markdown", ) st.markdown( "" "The three agent files carry a short preamble telling the tool this governs how it " "writes - commit messages, docs, replies - not how it writes code." "
", unsafe_allow_html=True, ) if st.button("Start over", use_container_width=False): st.session_state.clear() st.rerun() st.write("---") st.subheader("Test Your New Persona") st.write("Chat with the AI using your newly generated system prompt to see how it sounds!") if 'chat_history' not in st.session_state: st.session_state['chat_history'] = [] for message in st.session_state['chat_history']: with st.chat_message(message["role"]): st.markdown(message["content"]) if user_input := st.chat_input("Say something to your AI companion..."): st.session_state['chat_history'].append({"role": "user", "content": user_input}) with st.chat_message("user"): st.markdown(user_input) with st.chat_message("assistant"): with st.spinner("Thinking..."): try: response_text = chat_gemini(api_key, model_id, st.session_state.final_prompt, st.session_state['chat_history'][:-1], user_input) st.markdown(response_text) st.session_state['chat_history'].append({"role": "assistant", "content": response_text}) except Exception as e: st.error(f"Chat error: {e}")