Spaces:
Sleeping
Sleeping
Download app.py from manifestation-tools/ImagineToReality: direct link, hf CLI and curl.
- Browser
- Download file 7 kB
-
https://huggingface.co/spaces/manifestation-tools/ImagineToReality/resolve/main/app.py
- Command line
-
hf download hf://spaces/manifestation-tools/ImagineToReality/app.py
-
curl -L -o app.py https://huggingface.co/spaces/manifestation-tools/ImagineToReality/resolve/main/app.py
7 kB
| import gradio as gr | |
| import requests | |
| import os | |
| import uuid | |
| import asyncio | |
| import edge_tts | |
| import re | |
| import emoji | |
| from pydub import AudioSegment | |
| from num2words import num2words | |
| VOICE = "en-US-GuyNeural" | |
| def clean_text(text): | |
| text = emoji.replace_emoji(text, replace="") | |
| text = re.sub(r'[*_#"`]', '', text) | |
| text = text.replace("\\", "").strip() | |
| currency_map = { | |
| 'rs': 'rupees', 'inr': 'rupees', | |
| 'usd': 'dollars', '$': 'dollars', | |
| 'eur': 'euros', '€': 'euros', | |
| 'gbp': 'pounds', '£': 'pounds', | |
| 'cad': 'Canadian dollars', | |
| 'aud': 'Australian dollars', | |
| 'jpy': 'yen', '¥': 'yen', 'yen': 'yen', | |
| 'aed': 'dirhams', 'dirham': 'dirhams', | |
| 'btc': 'bitcoins', 'bitcoin': 'bitcoins' | |
| } | |
| unit_map = { | |
| 'sqft': 'square feet', 'sq ft': 'square feet', 'sq. ft': 'square feet', | |
| 'sqmt': 'square meters', 'sq m': 'square meters', 'sq. m': 'square meters', | |
| 'km2': 'square kilometers', 'km': 'kilometers', | |
| 'm2': 'square meters', 'm': 'meters', 'cm': 'centimeters', 'mm': 'millimeters', | |
| 'in': 'inches', 'inch': 'inches', | |
| 'acres': 'acres', 'acre': 'acres', | |
| 'hectare': 'hectares', 'hectares': 'hectares', | |
| 'mile': 'miles', 'miles': 'miles', | |
| 'yard': 'yards', 'yards': 'yards', | |
| 'kg': 'kilograms', 'kgs': 'kilograms', | |
| 'g': 'grams', 'gm': 'grams', 'gms': 'grams', | |
| 'l': 'litres', 'ltr': 'litres', 'litre': 'litres', 'litres': 'litres', | |
| 'ml': 'millilitres', | |
| 'ton': 'tons', 'tons': 'tons', 'tonne': 'tons', 'tonnes': 'tons' | |
| } | |
| def replace_currency(match): | |
| num = match.group(1).replace(',', '') | |
| curr = match.group(2).lower() | |
| if curr in currency_map: | |
| try: | |
| word_num = num2words(int(num), lang='en', to='cardinal').replace('-', ' ') | |
| return f"{word_num} {currency_map[curr]}" | |
| except: | |
| return match.group(0) | |
| return match.group(0) | |
| def replace_units(match): | |
| num = match.group(1).replace(',', '') | |
| unit = match.group(2).lower() | |
| if unit in unit_map: | |
| try: | |
| word_num = num2words(int(num), lang='en', to='cardinal').replace('-', ' ') | |
| return f"{word_num} {unit_map[unit]}" | |
| except: | |
| return match.group(0) | |
| return match.group(0) | |
| def replace_general_numbers(match): | |
| try: | |
| number = match.group(0).replace(',', '') | |
| return num2words(int(number), lang='en', to='cardinal').replace('-', ' ') | |
| except: | |
| return match.group(0) | |
| text = re.sub(r'\b(\d{1,3}(?:,\d{3})*)\s*(rs|usd|inr|eur|gbp|cad|aud|yen|jpy|btc|aed|\$|\u20ac|\u00a3|\u00a5)\b', | |
| replace_currency, text, flags=re.IGNORECASE) | |
| text = re.sub(r'\b(\d{1,3}(?:,\d{3})*)\s*(' + '|'.join(re.escape(u) for u in unit_map.keys()) + ')\b', | |
| replace_units, text, flags=re.IGNORECASE) | |
| text = re.sub(r'\b\d{1,3}(?:,\d{3})*\b', replace_general_numbers, text) | |
| return text | |
| def add_fake_pauses(text): | |
| return re.sub(r'([.!?])', r'\1 ...', text) | |
| def generate_script(desire): | |
| prompt = f"""You are a manifestation coach. Take the following desire: | |
| \"{desire}\" | |
| Generate a magical, emotionally inspiring manifestation script in first person, present tense. Do not include affirmations. Use vivid sensory details and hypnotic storytelling as per Neville Goddard’s philosophy. | |
| Use one or two exclamatory marks (!) in the script at emotionally intense or climactic moments — use them rarely but mandatorily to create dramatic impact.""" | |
| try: | |
| res = requests.post( | |
| "https://openrouter.ai/api/v1/chat/completions", | |
| headers={ | |
| "Authorization": f"Bearer {os.getenv('OPENROUTER_API_KEY')}", | |
| "Content-Type": "application/json" | |
| }, | |
| json={ | |
| "model": "deepseek/deepseek-chat-v3-0324", | |
| "messages": [ | |
| {"role": "system", "content": "You are a master manifestation coach using Neville Goddard’s techniques."}, | |
| {"role": "user", "content": prompt} | |
| ] | |
| } | |
| ) | |
| response_json = res.json() | |
| print("[DEBUG] Response JSON:", response_json) | |
| content = response_json["choices"][0]["message"]["content"] | |
| return extract_user_script(content) | |
| except Exception as e: | |
| return f"Error generating script: {e}" | |
| def extract_user_script(content): | |
| lines = content.splitlines() | |
| script_lines = [line for line in lines if not line.strip().startswith(("You are", "Prompt:", "\"", "`", "*"))] | |
| return "\n".join(script_lines).strip() | |
| async def tts_to_file(text): | |
| cleaned = clean_text(text) | |
| paused = add_fake_pauses(cleaned) | |
| final_audio = AudioSegment.silent(duration=500) | |
| try: | |
| chimes = AudioSegment.from_file("chimes.mp3") - 10 | |
| bgm = AudioSegment.from_file("bgm.mp3") - 15 | |
| except: | |
| chimes = AudioSegment.silent(duration=300) | |
| bgm = AudioSegment.silent(duration=1000) | |
| parts = re.split(r'(!)', paused) | |
| full_phrases = [p1 + p2 if p2 == '!' else p1 for p1, p2 in zip(parts[::2], parts[1::2])] + parts[len(parts)//2*2:] | |
| for part in full_phrases: | |
| if not part.strip(): | |
| continue | |
| tts_path = f"/tmp/{uuid.uuid4()}.mp3" | |
| try: | |
| communicate = edge_tts.Communicate( | |
| text=part, | |
| voice=VOICE, | |
| rate="-40%", | |
| pitch="-15Hz" | |
| ) | |
| await communicate.save(tts_path) | |
| speech = AudioSegment.from_file(tts_path) | |
| final_audio += speech | |
| if part.strip().endswith("!"): | |
| final_audio += chimes | |
| except Exception as e: | |
| print(f"[ERROR in edge-tts]: {e}") | |
| continue | |
| bgm = bgm[:len(final_audio)].fade_out(3000) | |
| bgm_looped = (bgm * ((len(final_audio) // len(bgm)) + 1))[:len(final_audio)] | |
| combined = final_audio.overlay(bgm_looped) | |
| final_file = f"/tmp/{uuid.uuid4()}_final.mp3" | |
| combined.export(final_file, format="mp3") | |
| return final_file | |
| def full_pipeline(desire): | |
| script = generate_script(desire) | |
| if script.startswith("Error"): | |
| return script, None | |
| word_count = len(clean_text(script).split()) | |
| print(f"[INFO] Word Count: {word_count}") | |
| audio_path = asyncio.run(tts_to_file(script)) | |
| return script, audio_path | |
| with gr.Blocks() as demo: | |
| gr.Markdown("## 👑 ImagineToReality") | |
| user_input = gr.Textbox(label="What do you want to manifest?") | |
| gen_button = gr.Button("✨ Generate") | |
| with gr.Row(): | |
| script_output = gr.Textbox(label="Script", lines=10) | |
| audio_output = gr.Audio(label="Playback", autoplay=True) | |
| gen_button.click(fn=full_pipeline, inputs=user_input, outputs=[script_output, audio_output]) | |
| demo.queue().launch(show_api=True) | |