Spaces:
Runtime error
Runtime error
import gradio as gr | |
import random | |
import re | |
import json | |
from pathlib import Path | |
from huggingface_hub import InferenceClient, snapshot_download | |
import shutil | |
def prepare_tarot_dataset(): | |
repo_id = "multimodalart/1920-raider-waite-tarot-public-domain" | |
dataset_path = Path("tarot_dataset") | |
image_dir = dataset_path / "images" | |
image_dir.mkdir(parents=True, exist_ok=True) | |
# Descargar repositorio completo | |
repo_path = snapshot_download(repo_id=repo_id, repo_type="dataset") | |
# Procesar archivo JSONL manualmente | |
jsonl_path = Path(repo_path) / "output_file.jsonl" | |
card_map = {} | |
pattern = re.compile(r'"([^"]+)"$') | |
with open(jsonl_path, "r") as f: | |
for line in f: | |
try: | |
data = json.loads(line) | |
text = data["text"] | |
file_name = data["file_name"] | |
# Extraer nombre de la carta | |
match = pattern.search(text) | |
if match: | |
card_name = match.group(1).lower().replace('"', '') | |
src_image = Path(repo_path) / file_name | |
dest_image = image_dir / f"{card_name.replace(' ', '_')}.jpg" | |
if not dest_image.exists(): | |
shutil.copy(src_image, dest_image) | |
card_map[card_name] = str(dest_image) | |
except (KeyError, json.JSONDecodeError) as e: | |
print(f"Error procesando línea: {e}") | |
continue | |
return card_map | |
# Preparar dataset y obtener mapeo de cartas | |
CARD_MAP = prepare_tarot_dataset() | |
CARDS = list(CARD_MAP.keys()) | |
# System Prompt mejorado | |
TAROTIST_PROMPT = """ | |
Eres Madame Esmeralda, vidente tercera generación con dones psíquicos. Tu estilo: | |
🔮 Combinas simbolismo cabalístico, astrología y quiromancia | |
🌙 Usas un lenguaje poético con rimas sutiles | |
💫 Incluye predicciones a 3 plazos (corto, medio y largo) | |
🌿 Relaciona las cartas con elementos naturales | |
✨ Termina con un presagio y recomendación mágica | |
Técnica de lectura: | |
1. Analiza posición cósmica actual | |
2. Desentraña relaciones kármicas | |
3. Revela desafíos ocultos | |
4. Señala oportunidades místicas | |
5. Ofrece protección espiritual | |
Formato respuesta: | |
📜 **Profecía Celestial** (emoji relacionado) | |
Verso poético de 4 líneas | |
🌌 **Desglose Arcano**: | |
- Influencia planetaria | |
- Elemento dominante | |
- Chakras afectados | |
🗝️ **Clave del Destino**: | |
Consejo práctico con hierba/color/cristal | |
""" | |
client = InferenceClient(provider="hf-inference", api_key="hf_xxxxxxxxxxxxxxxxxxxxxxxx") | |
def get_reading(cards): | |
messages = [ | |
{"role": "system", "content": TAROTIST_PROMPT}, | |
{"role": "user", "content": f"Realiza lectura completa para: {', '.join(cards)}. Incluye predicciones temporales."} | |
] | |
completion = client.chat.completions.create( | |
model="meta-llama/Llama-3.3-70B-Instruct", | |
messages=messages, | |
max_tokens=700, | |
) | |
return completion.choices[0].message.content | |
def draw_cards(spread_type): | |
spreads = { | |
"Oráculo Rápido": 1, | |
"Tríada del Destino": 3, | |
"Cruz Mística": 5, | |
"Círculo Zodiacal": 12 | |
} | |
num_cards = spreads.get(spread_type, 3) | |
drawn = random.sample(CARDS, num_cards) | |
images = [CARD_MAP[card] for card in drawn if card in CARD_MAP] | |
return images, drawn | |
def process_spread(spread_type): | |
images, cards = draw_cards(spread_type) | |
return images, "\n".join(f"🔮 {c.capitalize()}" for c in cards) | |
def full_reading(_, cards_text): | |
cards = [line.replace("🔮 ", "").lower() for line in cards_text.split("\n")] | |
reading = get_reading(cards) | |
return f"## 📜 Lectura Mística 📜\n\n{reading}" | |
with gr.Blocks(theme=gr.themes.Soft(primary_hue="purple")) as demo: | |
gr.Markdown("# <center>🔮 Vidente del Alma 🔮</center>") | |
with gr.Row(variant="panel"): | |
gr.Image("mystic_banner.png", label="Madame Esmeralda", width=200) | |
with gr.Column(): | |
spread_btn = gr.Radio( | |
choices=["Oráculo Rápido", "Tríada del Destino", "Cruz Mística", "Círculo Zodiacal"], | |
label="Selección del Oráculo", | |
elem_classes="mystic-radio" | |
) | |
draw_btn = gr.Button("🌌 Invocar Cartas 🌌", variant="primary") | |
with gr.Row(): | |
gallery = gr.Gallery( | |
label="Cartas Invocadas", | |
columns=6, | |
height=300, | |
object_fit="cover" | |
) | |
cards_text = gr.Textbox( | |
label="Energías Reveladas", | |
interactive=False, | |
elem_classes="mystic-text" | |
) | |
reading_btn = gr.Button("🧿 Revelar Profecía 🧿", variant="primary") | |
reading_output = gr.Markdown("### Que los astros guíen tu camino...", elem_id="prophecy-box") | |
draw_btn.click( | |
process_spread, | |
inputs=spread_btn, | |
outputs=[gallery, cards_text] | |
) | |
reading_btn.click( | |
full_reading, | |
inputs=[spread_btn, cards_text], | |
outputs=reading_output | |
) | |
if __name__ == "__main__": | |
demo.launch( | |
css=".mystic-radio {color: #4a148c} .mystic-text {font-family: 'Papyrus'} #prophecy-box {background: #f3e5f5}" | |
) |