Spaces:
Runtime error
Runtime error
File size: 5,027 Bytes
a981dce |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 |
import gradio as gr
import random
import re
from pathlib import Path
from huggingface_hub import InferenceClient, snapshot_download
from datasets import load_dataset
import shutil
# Descargar y preparar dataset de tarot
def prepare_tarot_dataset():
dataset_path = Path("tarot_dataset")
image_dir = dataset_path / "images"
image_dir.mkdir(parents=True, exist_ok=True)
# Descargar dataset
dataset = load_dataset("multimodalart/1920-raider-waite-tarot-public-domain", split="train")
# Procesar metadatos y organizar imágenes
card_map = {}
pattern = re.compile(r'"([^"]+)"$') # Para extraer el nombre de la carta
for item in dataset:
text = item["text"]
match = pattern.search(text)
if match:
card_name = match.group(1).lower()
src_path = Path(item["file_name"])
dest_path = image_dir / f"{card_name.replace(' ', '_')}.jpg"
if not dest_path.exists():
try:
# Copiar imagen desde el dataset descargado
shutil.copy(src_path, dest_path)
except:
continue
card_map[card_name] = str(dest_path)
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}"
) |