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"
", unsafe_allow_html=True) st.markdown("

Your Fairy Prompt-Mother

", unsafe_allow_html=True) st.markdown("

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("

1. Upload
Drop text or PDFs.
", unsafe_allow_html=True) with col2: st.markdown("

2. Analyze
Answer AI questions.
", unsafe_allow_html=True) with col3: st.markdown("

3. Clone
Download the prompt.
", unsafe_allow_html=True) st.write("---") # ---- Two ways to use it -------------------------------------------- st.markdown("

Two ways to use it

", unsafe_allow_html=True) col_web, col_cli = st.columns([1, 1.15]) with col_web: st.markdown( "
" "
" "  " "Right here, in the browser
" "

" "Upload a handful of files and go. Nothing to install, nothing to sign up for." "

" "

" "Best for trying it, or for one quick persona.

" "
", unsafe_allow_html=True, ) with col_cli: st.markdown( "
" "
" "  In your terminal - point it at everything
" "

" "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.

" "
", unsafe_allow_html=True, ) st.write("") st.markdown( "

" "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("

How it works

", unsafe_allow_html=True) 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( "
" "How PixieDuster works" "
", unsafe_allow_html=True, ) st.write("---") # Clean, linear layout instead of erratic columns st.markdown("### 1. Identify the Persona") target_input = st.text_input( "Whose voice are we cloning?", placeholder="e.g., Myself, A 1920s detective, My best friend Sarah..." ) target_name = target_input if target_input else "the author" st.markdown("### 2. Upload Writing Samples") with st.expander("💡 What makes a perfect sample?", expanded=True): st.write("For the most accurate psychological profiling, we recommend **3 to 5 samples** across different contexts:") st.markdown( "- **Informal:** A chat log, casual email, or social media post.\n" "- **Formal:** An essay, professional report, or dissertation.\n" "- **Multimodal:** We accept text files, PDFs, and even **screenshots of handwriting or chat bubbles** (PNG/JPG)!" ) uploaded_files = st.file_uploader( "Drop files here", accept_multiple_files=True, type=['txt', 'pdf', 'png', 'jpg', 'jpeg'], label_visibility="collapsed" ) st.write("---") analyze_btn = st.button("Begin Analysis", use_container_width=True) if analyze_btn: if uploaded_files: st.session_state.target_name = target_name with st.status("Running Analysis...", expanded=True) as status: try: st.markdown(" Inspecting your writing samples...", unsafe_allow_html=True) # Convert UploadedFile objects to in-memory objects immediately # so they survive when the file_uploader widget is unmounted in Step 2. class MemFile: def __init__(self, name, type, data): self.name = name self.type = type self.data = data def getvalue(self): return self.data mem_files = [MemFile(f.name, f.type, f.getvalue()) for f in uploaded_files] st.session_state.uploaded_genai_files = mem_files st.markdown(" Formulating profiling questions...", unsafe_allow_html=True) prompt_instruction = ( f"Analyze the provided writing samples belonging to '{target_name}'. " "Formulate 3 highly specific multiple-choice questions to ask the author to uncover deep personality quirks, cognitive styles, or stylistic choices that aren't perfectly obvious from the text alone. " "Output the result STRICTLY as valid JSON with the following schema: " '{"questions": [{"question": "...", "options": ["...", "..."]}]}' ) time.sleep(0.1) # Force UI to render before blocking network request response_text = call_gemini(api_key, model_id, prompt_instruction, mem_files, require_json=True, op="interview") clean_text = response_text.strip() if clean_text.startswith("```json"): clean_text = clean_text[7:] elif clean_text.startswith("```"): clean_text = clean_text[3:] if clean_text.endswith("```"): clean_text = clean_text[:-3] clean_text = clean_text.strip() try: st.session_state.questions_data = json.loads(clean_text) except json.JSONDecodeError as e: raise Exception("The AI generated a malformed JSON payload (likely an unescaped quote). Please click 'Begin Analysis' again to let it retry!") status.update(label="Analysis Complete!", state="complete", expanded=False) time.sleep(0.5) st.session_state.step = 2 st.rerun() except Exception as e: status.update(label="Analysis Failed", state="error") st.error(f"An error occurred: {e}") else: st.warning("Please upload at least one writing sample.") # --- STEP 2: INTERACTIVE Q&A --- elif st.session_state.step == 2: st.subheader("Clarifying the Magic") st.write(f"To perfectly calibrate '{st.session_state.target_name}', please select the most accurate answers below:") user_selections = [] # Render multiple choice questions if isinstance(st.session_state.questions_data, list): questions = st.session_state.questions_data elif isinstance(st.session_state.questions_data, dict): questions = st.session_state.questions_data.get('questions', []) else: questions = [] for i, q in enumerate(questions): st.markdown(f"**{i+1}. {q['question']}**") ans = st.radio(f"Options for Q{i+1}", q['options'], key=f"q_{i}", label_visibility="collapsed") user_selections.append(f"Q: {q['question']}\nA: {ans}") st.write("") # spacing user_answers_formatted = "\n\n".join(user_selections) st.write("---") col1, col2 = st.columns(2) with col1: if st.button("Go Back"): st.session_state.step = 1 st.rerun() with col2: if st.button("Generate Final Prompt"): if user_answers_formatted: with st.status("Generating Final Persona...", expanded=True) as status: try: st.markdown(" Compiling persona data...", unsafe_allow_html=True) final_instruction = ( f"Here are the original writing samples for '{st.session_state.target_name}'. " f"I also asked the user some multiple choice questions to refine the persona.\n" f"Here are their answers:\n{user_answers_formatted}\n\n" "PSYCHOLOGICAL & EMPIRICAL PROFILING RUBRIC:\n" "You must evaluate the text and answers strictly using the following empirical rubrics:\n" "1. LIWC Lexical/Syntactic Fingerprint: Analyze Pronoun Orientation (1st person singular vs plural vs 2nd/3rd), Affective Processes (Positive vs Negative Emotion clusters), Cognitive Processes (Insight, Causation, Tentativeness vs Certainty), and Temporal Orientation (Past/Present/Future).\n" "2. The Big Five (OCEAN): Map linguistic data to Openness, Conscientiousness, Extraversion, Agreeableness, and Neuroticism based on lexical richness, structure, social words, hedging, and self-doubt.\n" "3. Cognitive Style & Epistemic Stance: Is the author analytical or narrative? Do they rely on empirical citations, personal anecdotes, or axioms? Do they display dialectical thinking or binary/dogmatic thinking?\n" "4. Sociolinguistics: Document academic vs colloquial register, specific jargon, syntactic rhythm (staccato vs winding), and punctuation quirks.\n" "5. Humor (Peter McGraw's Benign Violation Theory): Work out from the evidence whether this person is funny, how often, and by what mechanism. Humor happens when something violates a norm while simultaneously staying benign; violation alone is hostility, benign alone is bland. Identify which norms this author is willing to violate, what keeps those violations safe, and how dry or broad the delivery is. If the evidence shows someone who rarely jokes, say so plainly and specify restraint rather than inventing wit they do not have. If it shows someone consistently funny, give the specific rules and one example line in their voice. Never produce plain malignant jabs, and never separate the violation from the benign frame.\n\n" "Based on ALL of this, extract their unique terminology standard, recurring thought patterns, sentence structure, and overall persona. " "Output ONLY the extracted 'Terminology Standards & Persona' summary designed to be injected directly into a system prompt. Do not include any conversational filler." ) st.markdown(" Evaluating Big Five personality traits...", unsafe_allow_html=True) time.sleep(0.4) st.markdown(" Analyzing LIWC syntax and pronoun orientation...", unsafe_allow_html=True) time.sleep(0.4) st.markdown(" Assessing cognitive style...", unsafe_allow_html=True) time.sleep(0.4) st.markdown(" Mapping sociolinguistics...", unsafe_allow_html=True) time.sleep(0.1) # Force UI to render before blocking network request extracted_persona = call_gemini(api_key, model_id, final_instruction, st.session_state.uploaded_genai_files, require_json=False) st.session_state.final_prompt = ANTI_AI_PROMPT_TEMPLATE.replace("{extracted_persona}", extracted_persona) status.update(label="Persona Generated Successfully!", state="complete", expanded=False) time.sleep(0.5) st.session_state.step = 3 st.rerun() except Exception as e: status.update(label="Analysis Failed", state="error") st.error(f"An error occurred: {e}") else: st.warning("Please provide some answers to help the AI.") # --- STEP 3: FINAL DELIVERABLE & CHAT --- elif st.session_state.step == 3: st.success("Your Custom Persona Prompt is Ready!") if True: import re import html safe_prompt = html.escape(st.session_state.final_prompt) # Replace headers html_prompt = re.sub(r'(?m)^### (.*?)$', r'

\1

', safe_prompt) html_prompt = re.sub(r'(?m)^## (.*?)$', r'

\1

', html_prompt) html_prompt = re.sub(r'(?m)^# (.*?)$', r'

\1

', html_prompt) # Replace bold html_prompt = re.sub(r'\*\*(.*?)\*\*', r'\1', html_prompt) # Replace italics html_prompt = re.sub(r'\*(.*?)\*', r'\1', html_prompt) # Replace list items html_prompt = re.sub(r'(?m)^\* (.*?)$', r'
  • \1
  • ', html_prompt) html_prompt = re.sub(r'(?m)^- (.*?)$', r'
  • \1
  • ', html_prompt) # Wrap paragraphs paragraphs = html_prompt.split('\n\n') wrapped_paragraphs = [] for p in paragraphs: if '{p.replace(chr(10), "
    ")}

    ') html_prompt = "".join(wrapped_paragraphs) certificate_html = f'''

    CERTIFICATE OF PERSONA

    Officially cloned for: {st.session_state.target_name.upper()}


    {html_prompt}

    Authorized by PixieDuster

    ''' st.markdown(certificate_html, unsafe_allow_html=True) st.write("---") st.markdown("

    Take it with you

    ", unsafe_allow_html=True) st.markdown( "

    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}")