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 = """ """ 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("
") # Submit — centred with gr.Row(): submit_btn = gr.Button("Hand Worry to the Universe ✨", variant="primary", elem_id="component-submit") gr.HTML("
") # 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()