randomvisitor's picture
Update app.py
0f2a79c verified
Raw
History Blame Contribute Delete
10.7 kB
import gradio as gr
import requests
import os
API_URL = "https://api-inference.huggingface.co/models/Qwen/Qwen2.5-7B-Instruct"
SYSTEM_PROMPT = (
"You are a wise, slightly witty, and deeply philosophical cosmic guide. "
"The user will share a minor daily human anxiety. Reframe their problem entirely from the "
"perspective of their chosen cosmic scale. Keep your response strictly under 4 sentences. "
"Make it comforting but funny, proving how wonderfully small their problem is in the grand timeline of reality."
)
def generate_cosmic_response(worry, scale):
if not worry.strip():
return "Please type a worry so the universe can handle it!"
formatted_prompt = (
f"<|im_start|>system\n{SYSTEM_PROMPT}<|im_end|>\n"
f"<|im_start|>user\nMy worry is: '{worry}'. Reframe it from this perspective: {scale}.<|im_end|>\n"
f"<|im_start|>assistant\n"
)
payload = {
"inputs": formatted_prompt,
"parameters": {
"max_new_tokens": 200,
"temperature": 0.7,
"return_full_text": False
}
}
# Automatically use Space token if available to bypass strict rate limits
headers = {}
if os.getenv("HF_TOKEN"):
headers["Authorization"] = f"Bearer {os.getenv('HF_TOKEN')}"
try:
# INCREASED TIMEOUT to 60 seconds to allow the model time to wake up
response = requests.post(API_URL, json=payload, headers=headers, timeout=60)
# Safely handle overloaded Hugging Face servers without crashing
if response.status_code != 200:
try:
error_data = response.json()
if "error" in error_data:
return f"The universe is booting up: {error_data['error']}. Wait 20 seconds and try again!"
except:
pass
return f"The universe is experiencing high traffic (Status {response.status_code}). Give it a minute!"
output = response.json()
if isinstance(output, list) and len(output) > 0:
generated_text = output[0].get('generated_text', '').strip()
return generated_text.replace("<|im_end|>", "").strip()
elif isinstance(output, dict) and "error" in output:
return f"The universe is booting up: {output['error']}. Give it a brief moment and try again!"
return "The stars are misaligned. Try pressing the button once more."
except requests.exceptions.Timeout:
return "The stars are taking a while to align! The model is still waking up. Please click the button again."
except Exception as e:
return f"Cosmic connection error: {str(e)}. Take a deep breath and try again!"
head = """
<link href="https://fonts.googleapis.com/css2?family=Hanken+Grotesk:wght@400;600;700;800;900&display=swap" rel="stylesheet"/>
<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:wght,FILL@100..700,0..1&display=swap" rel="stylesheet"/>
<style>
/* ── Reset & base ── */
*, *::before, *::after { box-sizing: border-box; }
body, .gradio-container {
background-color: #131313 !important;
color: #e5e2e1 !important;
font-family: 'Hanken Grotesk', sans-serif !important;
-webkit-font-smoothing: antialiased;
}
/* Hide default Gradio chrome we don't need */
.gradio-container > .main > .wrap { padding: 0 !important; }
footer { display: none !important; }
/* ── All text visible ── */
p, span, label, div, h1, h2, h3, h4, h5, h6,
.prose, .prose p,
[data-testid="markdown"], [data-testid="markdown"] p {
color: #e5e2e1 !important;
font-family: 'Hanken Grotesk', sans-serif !important;
overflow: visible !important;
max-height: none !important;
}
/* ── Hero title ── */
.cosmic-title [data-testid="markdown"] p,
.cosmic-title p {
font-size: clamp(36px, 6vw, 64px) !important;
font-weight: 900 !important;
line-height: 1.1 !important;
letter-spacing: -0.02em !important;
color: #e5e2e1 !important;
text-align: center !important;
}
/* ── Subtitle ── */
.cosmic-subtitle [data-testid="markdown"] p,
.cosmic-subtitle p {
font-size: 18px !important;
font-weight: 400 !important;
line-height: 1.6 !important;
color: #A1A1A1 !important;
text-align: center !important;
}
/* ── Section labels ── */
.cosmic-label [data-testid="markdown"] p,
.cosmic-label p {
font-size: 14px !important;
font-weight: 700 !important;
letter-spacing: 0.15em !important;
text-transform: uppercase !important;
color: #b4c5ff !important;
}
/* ── Textbox ── */
.gradio-container textarea {
background-color: #0e0e0e !important;
color: #e5e2e1 !important;
border: 1px solid #2D2D2D !important;
border-radius: 12px !important;
font-family: 'Hanken Grotesk', sans-serif !important;
font-size: 18px !important;
padding: 20px 24px !important;
}
.gradio-container textarea:focus {
border-color: #b4c5ff !important;
outline: none !important;
box-shadow: none !important;
}
.gradio-container .label-wrap { display: none !important; }
/* ── Tighten Gradio's default gaps ── */
.gradio-container .gap,
.gradio-container .flex-col {
gap: 4px !important;
}
.gradio-container .block {
padding: 4px 0 !important;
}
/* ── Kill ALL white/light backgrounds Gradio injects ── */
.gradio-container .block,
.gradio-container .form,
.gradio-container fieldset,
.gradio-container .wrap,
.gradio-container .gap,
.gradio-container > div,
.gradio-container .container,
.gradio-container .panel,
.gradio-container .tabs,
.gradio-container .tabitem,
.gradio-container .row,
.gradio-container .col,
.gradio-container .box {
background: transparent !important;
background-color: transparent !important;
border-color: transparent !important;
box-shadow: none !important;
}
/* Style each radio item as a card */
.gradio-container .block.svelte-1p9xokt label,
.gradio-container .wrap label,
.gradio-container input[type="radio"] + span {
background-color: #1c1b1b !important;
border: 1px solid #2D2D2D !important;
border-radius: 12px !important;
padding: 20px !important;
color: #e5e2e1 !important;
font-size: 14px !important;
font-weight: 600 !important;
transition: border-color 0.2s, background-color 0.2s !important;
cursor: pointer !important;
}
.gradio-container input[type="radio"]:checked + span,
.gradio-container .selected label {
border-color: #b4c5ff !important;
background-color: #1a1a1a !important;
}
/* ── Primary button ── */
.gradio-container button.primary,
#component-submit button {
background: #e5e2e1 !important;
color: #131313 !important;
font-family: 'Hanken Grotesk', sans-serif !important;
font-size: 14px !important;
font-weight: 700 !important;
letter-spacing: 0.02em !important;
border: none !important;
border-radius: 9999px !important;
padding: 14px 40px !important;
width: auto !important;
min-width: 280px !important;
max-width: 400px !important;
white-space: nowrap !important;
cursor: pointer !important;
transition: opacity 0.2s !important;
display: inline-flex !important;
align-items: center !important;
justify-content: center !important;
}
.gradio-container button.primary:hover { opacity: 0.88 !important; }
/* Wrapper row β€” kill excess padding and stop it squishing the button into a circle */
.gradio-container .row {
justify-content: center !important;
padding: 4px 0 !important;
gap: 0 !important;
}
/* ── Output card ── */
#reality-check-box {
background-color: #131313 !important;
border: 1px solid #2D2D2D !important;
border-radius: 12px !important;
padding: 32px !important;
position: relative !important;
overflow: hidden !important;
}
#reality-check-box::before {
content: '';
position: absolute;
inset: 0;
background: radial-gradient(circle at center, rgba(180,197,255,0.08) 0%, transparent 70%);
pointer-events: none;
}
#reality-check-box [data-testid="markdown"] p,
#reality-check-box p {
font-size: 24px !important;
font-weight: 700 !important;
line-height: 1.3 !important;
color: #c3c6d7 !important;
font-style: italic !important;
text-align: center !important;
}
/* ── Reality Check label above output ── */
.reality-label [data-testid="markdown"] p,
.reality-label p {
font-size: 12px !important;
font-weight: 700 !important;
letter-spacing: 0.2em !important;
text-transform: uppercase !important;
color: #b4c5ff !important;
text-align: center !important;
}
</style>
"""
SCALES = [
"A colony of ants living in your wall",
"The 4.5 billion year geological history of the Earth",
"A distant, indifferent supernova dying in another galaxy",
]
with gr.Blocks(theme=gr.themes.Monochrome(), head=head, css="") as demo:
# ── Hero ──
with gr.Column(elem_classes=["cosmic-title"]):
gr.Markdown("# πŸͺ The Cosmic Scale-Out")
with gr.Column(elem_classes=["cosmic-subtitle"]):
gr.Markdown(
"Anxiety grounding for busy minds. "
"Reframe your tiny daily struggles against the grand architecture of time and space."
)
with gr.Column():
# Worry input
with gr.Column(elem_classes=["cosmic-label"]):
gr.Markdown("What are you spiraling about right now?")
worry_input = gr.Textbox(
placeholder="e.g., I'm stressed about a presentation or a flight delay...",
lines=4,
show_label=False,
)
# Scale selector
with gr.Column(elem_classes=["cosmic-label"]):
gr.Markdown("Choose your cosmic scale factor:")
perspective_input = gr.Radio(
choices=SCALES,
value=SCALES[0],
show_label=False,
)
gr.HTML("<div style='height:8px'></div>")
# Submit β€” centred
with gr.Row():
submit_btn = gr.Button("Hand Worry to the Universe ✨", variant="primary", elem_id="component-submit")
gr.HTML("<div style='height:24px'></div>")
# Output
with gr.Column(elem_classes=["reality-label"]):
gr.Markdown("πŸͺ Reality Check")
output_text = gr.Markdown(elem_id="reality-check-box")
submit_btn.click(
fn=generate_cosmic_response,
inputs=[worry_input, perspective_input],
outputs=output_text,
)
demo.launch()