Spaces:
Sleeping
Sleeping
Perplexity LABS CURL
Browse files- README.md +25 -73
- app.py +95 -116
- requirements.txt +1 -3
- script.py +131 -220
README.md
CHANGED
|
@@ -1,100 +1,52 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
colorFrom: blue
|
| 5 |
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version: 4.
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
license: mit
|
| 11 |
---
|
| 12 |
|
| 13 |
-
#
|
| 14 |
|
| 15 |
-
|
| 16 |
|
| 17 |
-
##
|
| 18 |
|
| 19 |
-
-
|
| 20 |
-
-
|
| 21 |
-
-
|
| 22 |
-
-
|
| 23 |
-
- ✅ Soporte multiidioma
|
| 24 |
|
| 25 |
-
##
|
| 26 |
|
| 27 |
-
|
|
|
|
|
|
|
| 28 |
|
| 29 |
-
|
| 30 |
-
2. Selecciona **Gradio** como SDK
|
| 31 |
-
3. Nombra tu Space (ej: "title-generator-llama")
|
| 32 |
|
| 33 |
-
###
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
4. Añade un nuevo secret:
|
| 41 |
-
- **Name**: `HF_TOKEN`
|
| 42 |
-
- **Value**: Tu token de Hugging Face (empezará con `hf_...`)
|
| 43 |
-
|
| 44 |
-
### 3. Subir los archivos
|
| 45 |
-
|
| 46 |
-
Sube estos archivos a tu Space:
|
| 47 |
-
- `app.py` - Código principal
|
| 48 |
-
- `requirements.txt` - Dependencias
|
| 49 |
-
- `README.md` - Esta documentación
|
| 50 |
-
|
| 51 |
-
## Uso
|
| 52 |
-
|
| 53 |
-
### Interfaz Web
|
| 54 |
-
|
| 55 |
-
Simplemente visita tu Space y usa la interfaz para:
|
| 56 |
-
- **Texto Simple**: Pega cualquier texto y genera un título
|
| 57 |
-
- **Conversación**: Pega un historial de chat y genera un título resumido
|
| 58 |
|
| 59 |
-
###
|
| 60 |
|
| 61 |
```python
|
| 62 |
from gradio_client import Client
|
| 63 |
|
| 64 |
-
client = Client("
|
| 65 |
-
result = client.predict(
|
| 66 |
-
input_text="Tu texto aquí...",
|
| 67 |
-
is_conversation=False,
|
| 68 |
-
api_name="/predict"
|
| 69 |
-
)
|
| 70 |
print(result)
|
| 71 |
```
|
| 72 |
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
```javascript
|
| 76 |
-
import { Client } from "@gradio/client";
|
| 77 |
-
|
| 78 |
-
const client = await Client.connect("tu-usuario/title-generator-llama");
|
| 79 |
-
const result = await client.predict("/predict", {
|
| 80 |
-
input_text: "Tu texto aquí...",
|
| 81 |
-
is_conversation: false,
|
| 82 |
-
});
|
| 83 |
-
console.log(result.data);
|
| 84 |
-
```
|
| 85 |
-
|
| 86 |
-
### API HTTP
|
| 87 |
-
|
| 88 |
-
```bash
|
| 89 |
-
curl -X POST https://tu-usuario-title-generator-llama.hf.space/api/predict \
|
| 90 |
-
-H "Content-Type: application/json" \
|
| 91 |
-
-d '{"data": ["Tu texto aquí...", false]}'
|
| 92 |
-
```
|
| 93 |
-
|
| 94 |
-
## Hardware
|
| 95 |
-
|
| 96 |
-
Este Space funciona en **CPU básico** de Hugging Face (gratis). El modelo es lo suficientemente pequeño para ejecutarse eficientemente sin GPU.
|
| 97 |
-
|
| 98 |
-
## Licencia
|
| 99 |
|
| 100 |
MIT License
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Title Generator with Llama 3.2
|
| 3 |
+
emoji: 📝
|
| 4 |
colorFrom: blue
|
| 5 |
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 4.44.0
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
license: mit
|
| 11 |
---
|
| 12 |
|
| 13 |
+
# Title Generator with Llama 3.2-1B-Instruct
|
| 14 |
|
| 15 |
+
Generate concise titles from text or conversation history using Meta's Llama 3.2-1B-Instruct model.
|
| 16 |
|
| 17 |
+
## Features
|
| 18 |
|
| 19 |
+
- 📝 Generate titles from plain text
|
| 20 |
+
- 💬 Generate titles from conversation history
|
| 21 |
+
- 🚀 Fast inference with Llama 3.2-1B
|
| 22 |
+
- 🔌 RESTful API support for integration
|
|
|
|
| 23 |
|
| 24 |
+
## Setup
|
| 25 |
|
| 26 |
+
1. Go to your Space settings
|
| 27 |
+
2. Add a new secret: `HF_TOKEN` with your Hugging Face token
|
| 28 |
+
3. Make sure you have access to `meta-llama/Llama-3.2-1B-Instruct` (accept the gated model)
|
| 29 |
|
| 30 |
+
## API Usage
|
|
|
|
|
|
|
| 31 |
|
| 32 |
+
### CURL Example
|
| 33 |
|
| 34 |
+
```bash
|
| 35 |
+
curl -X POST "https://YOUR-SPACE-URL/call/generate_title" \
|
| 36 |
+
-H "Content-Type: application/json" \
|
| 37 |
+
-d '{"data": ["Your text or conversation here"]}'
|
| 38 |
+
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
+
### Python Example
|
| 41 |
|
| 42 |
```python
|
| 43 |
from gradio_client import Client
|
| 44 |
|
| 45 |
+
client = Client("YOUR-SPACE-URL")
|
| 46 |
+
result = client.predict("Your text here", api_name="/generate_title")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
print(result)
|
| 48 |
```
|
| 49 |
|
| 50 |
+
## License
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
MIT License
|
app.py
CHANGED
|
@@ -1,148 +1,127 @@
|
|
| 1 |
-
import os
|
| 2 |
import gradio as gr
|
| 3 |
-
|
| 4 |
-
import
|
| 5 |
-
|
| 6 |
-
# Obtener el token de HF desde
|
| 7 |
-
HF_TOKEN = os.
|
| 8 |
-
|
| 9 |
-
#
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, token=HF_TOKEN)
|
| 14 |
-
model = AutoModelForCausalLM.from_pretrained(
|
| 15 |
-
MODEL_NAME,
|
| 16 |
-
token=HF_TOKEN,
|
| 17 |
-
torch_dtype=torch.float16,
|
| 18 |
-
device_map="auto"
|
| 19 |
)
|
| 20 |
-
print("Modelo cargado exitosamente!")
|
| 21 |
|
| 22 |
-
def generate_title(
|
| 23 |
"""
|
| 24 |
-
Genera un título a partir de texto o historial de conversación
|
| 25 |
|
| 26 |
Args:
|
| 27 |
-
|
| 28 |
-
|
| 29 |
|
| 30 |
Returns:
|
| 31 |
-
|
| 32 |
"""
|
| 33 |
try:
|
| 34 |
-
#
|
| 35 |
-
if
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
| 38 |
else:
|
| 39 |
-
|
| 40 |
-
user_prompt = f"Texto:\n{input_text}\n\nGenera un título breve y descriptivo:"
|
| 41 |
|
| 42 |
-
#
|
| 43 |
-
|
| 44 |
-
{"role": "system", "content": system_prompt},
|
| 45 |
-
{"role": "user", "content": user_prompt}
|
| 46 |
-
]
|
| 47 |
|
| 48 |
-
|
| 49 |
-
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 50 |
|
| 51 |
-
|
| 52 |
-
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
| 53 |
|
| 54 |
-
# Generar
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
temperature=0.7,
|
| 59 |
-
top_p=0.9,
|
| 60 |
-
do_sample=True,
|
| 61 |
-
pad_token_id=tokenizer.eos_token_id
|
| 62 |
-
)
|
| 63 |
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
-
# Limpiar el título
|
| 68 |
-
title =
|
| 69 |
|
| 70 |
return title
|
| 71 |
|
| 72 |
except Exception as e:
|
| 73 |
-
return f"Error
|
| 74 |
-
|
| 75 |
-
# Crear interfaz de Gradio
|
| 76 |
-
with gr.Blocks(title="
|
| 77 |
-
gr.Markdown("#
|
| 78 |
-
gr.Markdown("
|
| 79 |
-
|
| 80 |
-
with gr.Tab("
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
placeholder="Escribe o pega el texto del que quieres generar un título...",
|
| 86 |
-
lines=8
|
| 87 |
-
)
|
| 88 |
-
text_btn = gr.Button("Generar Título", variant="primary")
|
| 89 |
-
|
| 90 |
-
with gr.Column():
|
| 91 |
-
text_output = gr.Textbox(label="Título generado", lines=3)
|
| 92 |
-
|
| 93 |
-
text_btn.click(
|
| 94 |
-
fn=lambda x: generate_title(x, is_conversation=False),
|
| 95 |
-
inputs=text_input,
|
| 96 |
-
outputs=text_output
|
| 97 |
)
|
|
|
|
|
|
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
],
|
| 104 |
-
inputs=text_input
|
| 105 |
)
|
| 106 |
|
| 107 |
-
with gr.Tab("
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
conv_input = gr.Textbox(
|
| 111 |
-
label="Historial de conversación",
|
| 112 |
-
placeholder="Pega aquí el historial de la conversación...\n\nFormato ejemplo:\nUsuario: Hola, ¿cómo estás?\nAsistente: ¡Bien! ¿En qué puedo ayudarte?",
|
| 113 |
-
lines=10
|
| 114 |
-
)
|
| 115 |
-
conv_btn = gr.Button("Generar Título", variant="primary")
|
| 116 |
-
|
| 117 |
-
with gr.Column():
|
| 118 |
-
conv_output = gr.Textbox(label="Título generado", lines=3)
|
| 119 |
-
|
| 120 |
-
conv_btn.click(
|
| 121 |
-
fn=lambda x: generate_title(x, is_conversation=True),
|
| 122 |
-
inputs=conv_input,
|
| 123 |
-
outputs=conv_output
|
| 124 |
-
)
|
| 125 |
|
| 126 |
-
gr.
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
)
|
| 133 |
|
|
|
|
|
|
|
| 134 |
gr.Markdown("""
|
| 135 |
-
|
| 136 |
-
- El modelo genera títulos concisos (máximo 6 palabras)
|
| 137 |
-
- Puedes usar tanto texto simple como conversaciones
|
| 138 |
-
- Funciona en español, inglés y otros idiomas
|
| 139 |
-
- Usa Llama 3.2-1B-Instruct de Meta
|
| 140 |
-
""")
|
| 141 |
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
|
|
|
|
|
|
| 146 |
|
|
|
|
| 147 |
if __name__ == "__main__":
|
| 148 |
-
demo.launch(
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
from huggingface_hub import InferenceClient
|
| 4 |
+
|
| 5 |
+
# Obtener el token de HF desde los secrets
|
| 6 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 7 |
+
|
| 8 |
+
# Inicializar el cliente de inferencia con el modelo Llama
|
| 9 |
+
client = InferenceClient(
|
| 10 |
+
model="meta-llama/Llama-3.2-1B-Instruct",
|
| 11 |
+
token=HF_TOKEN
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
)
|
|
|
|
| 13 |
|
| 14 |
+
def generate_title(text_or_history, max_length=50):
|
| 15 |
"""
|
| 16 |
+
Genera un título a partir de texto o historial de conversación
|
| 17 |
|
| 18 |
Args:
|
| 19 |
+
text_or_history: Puede ser texto simple o una lista de mensajes
|
| 20 |
+
max_length: Longitud máxima del título
|
| 21 |
|
| 22 |
Returns:
|
| 23 |
+
El título generado
|
| 24 |
"""
|
| 25 |
try:
|
| 26 |
+
# Si es una lista (historial), convertirla a texto
|
| 27 |
+
if isinstance(text_or_history, list):
|
| 28 |
+
# Formatear el historial como conversación
|
| 29 |
+
conversation_text = "\n".join([
|
| 30 |
+
f"{msg.get('role', 'user')}: {msg.get('content', '')}"
|
| 31 |
+
for msg in text_or_history
|
| 32 |
+
])
|
| 33 |
else:
|
| 34 |
+
conversation_text = str(text_or_history)
|
|
|
|
| 35 |
|
| 36 |
+
# Crear el prompt para generar título
|
| 37 |
+
prompt = f"""Based on the following conversation or text, generate a short, concise title (maximum 10 words):
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
+
{conversation_text}
|
|
|
|
| 40 |
|
| 41 |
+
Title:"""
|
|
|
|
| 42 |
|
| 43 |
+
# Generar el título usando el modelo
|
| 44 |
+
messages = [
|
| 45 |
+
{"role": "user", "content": prompt}
|
| 46 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
+
response = ""
|
| 49 |
+
for message in client.chat_completion(
|
| 50 |
+
messages=messages,
|
| 51 |
+
max_tokens=max_length,
|
| 52 |
+
temperature=0.7,
|
| 53 |
+
stream=True
|
| 54 |
+
):
|
| 55 |
+
token = message.choices[0].delta.content
|
| 56 |
+
if token:
|
| 57 |
+
response += token
|
| 58 |
|
| 59 |
+
# Limpiar el título (quitar saltos de línea extra, etc.)
|
| 60 |
+
title = response.strip().split("\n")[0]
|
| 61 |
|
| 62 |
return title
|
| 63 |
|
| 64 |
except Exception as e:
|
| 65 |
+
return f"Error: {str(e)}"
|
| 66 |
+
|
| 67 |
+
# Crear la interfaz de Gradio
|
| 68 |
+
with gr.Blocks(title="Title Generator with Llama 3.2") as demo:
|
| 69 |
+
gr.Markdown("# 📝 AI Title Generator")
|
| 70 |
+
gr.Markdown("Generate concise titles from text or conversation history using Llama 3.2-1B-Instruct")
|
| 71 |
+
|
| 72 |
+
with gr.Tab("Text Input"):
|
| 73 |
+
text_input = gr.Textbox(
|
| 74 |
+
label="Enter your text",
|
| 75 |
+
placeholder="Paste your text or conversation here...",
|
| 76 |
+
lines=10
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
)
|
| 78 |
+
text_button = gr.Button("Generate Title", variant="primary")
|
| 79 |
+
text_output = gr.Textbox(label="Generated Title", lines=2)
|
| 80 |
|
| 81 |
+
text_button.click(
|
| 82 |
+
fn=generate_title,
|
| 83 |
+
inputs=[text_input],
|
| 84 |
+
outputs=[text_output]
|
|
|
|
|
|
|
| 85 |
)
|
| 86 |
|
| 87 |
+
with gr.Tab("History/List Input"):
|
| 88 |
+
gr.Markdown("Enter conversation history as JSON format:")
|
| 89 |
+
gr.Markdown('Example: `[{"role": "user", "content": "Hello"}, {"role": "assistant", "content": "Hi there!"}]`')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
+
history_input = gr.Textbox(
|
| 92 |
+
label="Conversation History (JSON)",
|
| 93 |
+
placeholder='[{"role": "user", "content": "Your message here"}]',
|
| 94 |
+
lines=10
|
| 95 |
+
)
|
| 96 |
+
history_button = gr.Button("Generate Title", variant="primary")
|
| 97 |
+
history_output = gr.Textbox(label="Generated Title", lines=2)
|
| 98 |
+
|
| 99 |
+
def process_history(history_json):
|
| 100 |
+
try:
|
| 101 |
+
import json
|
| 102 |
+
history_list = json.loads(history_json)
|
| 103 |
+
return generate_title(history_list)
|
| 104 |
+
except json.JSONDecodeError:
|
| 105 |
+
return "Error: Invalid JSON format"
|
| 106 |
+
|
| 107 |
+
history_button.click(
|
| 108 |
+
fn=process_history,
|
| 109 |
+
inputs=[history_input],
|
| 110 |
+
outputs=[history_output]
|
| 111 |
)
|
| 112 |
|
| 113 |
+
gr.Markdown("---")
|
| 114 |
+
gr.Markdown("### API Usage")
|
| 115 |
gr.Markdown("""
|
| 116 |
+
You can use this API with CURL:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
+
```bash
|
| 119 |
+
curl -X POST "https://YOUR-SPACE-URL/call/generate_title" \
|
| 120 |
+
-H "Content-Type: application/json" \
|
| 121 |
+
-d '{"data": ["Your text here"]}'
|
| 122 |
+
```
|
| 123 |
+
""")
|
| 124 |
|
| 125 |
+
# Lanzar la aplicación con API habilitada
|
| 126 |
if __name__ == "__main__":
|
| 127 |
+
demo.launch(show_api=True)
|
requirements.txt
CHANGED
|
@@ -1,4 +1,2 @@
|
|
| 1 |
gradio>=4.0.0
|
| 2 |
-
|
| 3 |
-
torch>=2.0.0
|
| 4 |
-
accelerate>=0.20.0
|
|
|
|
| 1 |
gradio>=4.0.0
|
| 2 |
+
huggingface_hub>=0.19.0
|
|
|
|
|
|
script.py
CHANGED
|
@@ -1,297 +1,208 @@
|
|
| 1 |
|
| 2 |
-
#
|
| 3 |
-
#
|
| 4 |
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 9 |
-
import torch
|
| 10 |
|
| 11 |
-
# Obtener el token de HF desde
|
| 12 |
-
HF_TOKEN = os.
|
| 13 |
|
| 14 |
-
#
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, token=HF_TOKEN)
|
| 19 |
-
model = AutoModelForCausalLM.from_pretrained(
|
| 20 |
-
MODEL_NAME,
|
| 21 |
-
token=HF_TOKEN,
|
| 22 |
-
torch_dtype=torch.float16,
|
| 23 |
-
device_map="auto"
|
| 24 |
)
|
| 25 |
-
print("Modelo cargado exitosamente!")
|
| 26 |
|
| 27 |
-
def generate_title(
|
| 28 |
"""
|
| 29 |
-
Genera un título a partir de texto o historial de conversación
|
| 30 |
|
| 31 |
Args:
|
| 32 |
-
|
| 33 |
-
|
| 34 |
|
| 35 |
Returns:
|
| 36 |
-
|
| 37 |
"""
|
| 38 |
try:
|
| 39 |
-
#
|
| 40 |
-
if
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
| 43 |
else:
|
| 44 |
-
|
| 45 |
-
user_prompt = f"Texto:\\n{input_text}\\n\\nGenera un título breve y descriptivo:"
|
| 46 |
|
| 47 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
messages = [
|
| 49 |
-
{"role": "
|
| 50 |
-
{"role": "user", "content": user_prompt}
|
| 51 |
]
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
| 58 |
-
|
| 59 |
-
# Generar
|
| 60 |
-
outputs = model.generate(
|
| 61 |
-
**inputs,
|
| 62 |
-
max_new_tokens=50,
|
| 63 |
temperature=0.7,
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
| 68 |
|
| 69 |
-
#
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
# Limpiar el título
|
| 73 |
-
title = generated_text.strip().split('\\n')[0].strip()
|
| 74 |
|
| 75 |
return title
|
| 76 |
|
| 77 |
except Exception as e:
|
| 78 |
-
return f"Error
|
| 79 |
|
| 80 |
-
# Crear interfaz de Gradio
|
| 81 |
-
with gr.Blocks(title="
|
| 82 |
-
gr.Markdown("#
|
| 83 |
-
gr.Markdown("
|
| 84 |
|
| 85 |
-
with gr.Tab("
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
placeholder="Escribe o pega el texto del que quieres generar un título...",
|
| 91 |
-
lines=8
|
| 92 |
-
)
|
| 93 |
-
text_btn = gr.Button("Generar Título", variant="primary")
|
| 94 |
-
|
| 95 |
-
with gr.Column():
|
| 96 |
-
text_output = gr.Textbox(label="Título generado", lines=3)
|
| 97 |
-
|
| 98 |
-
text_btn.click(
|
| 99 |
-
fn=lambda x: generate_title(x, is_conversation=False),
|
| 100 |
-
inputs=text_input,
|
| 101 |
-
outputs=text_output
|
| 102 |
)
|
|
|
|
|
|
|
| 103 |
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
],
|
| 109 |
-
inputs=text_input
|
| 110 |
)
|
| 111 |
|
| 112 |
-
with gr.Tab("
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
conv_input = gr.Textbox(
|
| 116 |
-
label="Historial de conversación",
|
| 117 |
-
placeholder="Pega aquí el historial de la conversación...\\n\\nFormato ejemplo:\\nUsuario: Hola, ¿cómo estás?\\nAsistente: ¡Bien! ¿En qué puedo ayudarte?",
|
| 118 |
-
lines=10
|
| 119 |
-
)
|
| 120 |
-
conv_btn = gr.Button("Generar Título", variant="primary")
|
| 121 |
-
|
| 122 |
-
with gr.Column():
|
| 123 |
-
conv_output = gr.Textbox(label="Título generado", lines=3)
|
| 124 |
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
)
|
|
|
|
|
|
|
| 130 |
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
)
|
| 138 |
|
|
|
|
|
|
|
| 139 |
gr.Markdown("""
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
-
|
| 144 |
-
|
|
|
|
|
|
|
| 145 |
""")
|
| 146 |
|
| 147 |
-
#
|
| 148 |
-
# - Cliente Python de Gradio
|
| 149 |
-
# - Cliente JavaScript de Gradio
|
| 150 |
-
# - Llamadas HTTP directas
|
| 151 |
-
|
| 152 |
if __name__ == "__main__":
|
| 153 |
-
demo.launch(
|
| 154 |
'''
|
| 155 |
|
| 156 |
-
# Guardar
|
| 157 |
with open('app.py', 'w', encoding='utf-8') as f:
|
| 158 |
-
f.write(
|
| 159 |
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
requirements_txt = '''gradio>=4.0.0
|
| 164 |
-
transformers>=4.43.0
|
| 165 |
-
torch>=2.0.0
|
| 166 |
-
accelerate>=0.20.0
|
| 167 |
'''
|
| 168 |
|
| 169 |
with open('requirements.txt', 'w', encoding='utf-8') as f:
|
| 170 |
-
f.write(
|
| 171 |
-
|
| 172 |
-
print("✅ Archivo requirements.txt creado")
|
| 173 |
|
| 174 |
-
# Crear README
|
| 175 |
-
|
| 176 |
-
title:
|
| 177 |
-
emoji:
|
| 178 |
colorFrom: blue
|
| 179 |
colorTo: purple
|
| 180 |
sdk: gradio
|
| 181 |
-
sdk_version: 4.
|
| 182 |
app_file: app.py
|
| 183 |
pinned: false
|
| 184 |
license: mit
|
| 185 |
---
|
| 186 |
|
| 187 |
-
#
|
| 188 |
-
|
| 189 |
-
Esta aplicación genera títulos concisos a partir de texto o conversaciones usando el modelo **meta-llama/Llama-3.2-1B-Instruct**.
|
| 190 |
-
|
| 191 |
-
## Características
|
| 192 |
-
|
| 193 |
-
- ✅ Interfaz web interactiva con Gradio
|
| 194 |
-
- ✅ Generación de títulos desde texto simple o conversaciones
|
| 195 |
-
- ✅ API accesible mediante Python, JavaScript y HTTP
|
| 196 |
-
- ✅ Modelo ligero y rápido (1B parámetros)
|
| 197 |
-
- ✅ Soporte multiidioma
|
| 198 |
-
|
| 199 |
-
## Configuración
|
| 200 |
|
| 201 |
-
|
| 202 |
|
| 203 |
-
|
| 204 |
-
2. Selecciona **Gradio** como SDK
|
| 205 |
-
3. Nombra tu Space (ej: "title-generator-llama")
|
| 206 |
|
| 207 |
-
|
|
|
|
|
|
|
|
|
|
| 208 |
|
| 209 |
-
|
| 210 |
|
| 211 |
-
1.
|
| 212 |
-
2.
|
| 213 |
-
3.
|
| 214 |
-
4. Añade un nuevo secret:
|
| 215 |
-
- **Name**: `HF_TOKEN`
|
| 216 |
-
- **Value**: Tu token de Hugging Face (empezará con `hf_...`)
|
| 217 |
|
| 218 |
-
|
| 219 |
|
| 220 |
-
|
| 221 |
-
- `app.py` - Código principal
|
| 222 |
-
- `requirements.txt` - Dependencias
|
| 223 |
-
- `README.md` - Esta documentación
|
| 224 |
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
- **Texto Simple**: Pega cualquier texto y genera un título
|
| 231 |
-
- **Conversación**: Pega un historial de chat y genera un título resumido
|
| 232 |
|
| 233 |
-
###
|
| 234 |
|
| 235 |
```python
|
| 236 |
from gradio_client import Client
|
| 237 |
|
| 238 |
-
client = Client("
|
| 239 |
-
result = client.predict(
|
| 240 |
-
input_text="Tu texto aquí...",
|
| 241 |
-
is_conversation=False,
|
| 242 |
-
api_name="/predict"
|
| 243 |
-
)
|
| 244 |
print(result)
|
| 245 |
```
|
| 246 |
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
```javascript
|
| 250 |
-
import { Client } from "@gradio/client";
|
| 251 |
-
|
| 252 |
-
const client = await Client.connect("tu-usuario/title-generator-llama");
|
| 253 |
-
const result = await client.predict("/predict", {
|
| 254 |
-
input_text: "Tu texto aquí...",
|
| 255 |
-
is_conversation: false,
|
| 256 |
-
});
|
| 257 |
-
console.log(result.data);
|
| 258 |
-
```
|
| 259 |
-
|
| 260 |
-
### API HTTP
|
| 261 |
-
|
| 262 |
-
```bash
|
| 263 |
-
curl -X POST https://tu-usuario-title-generator-llama.hf.space/api/predict \\
|
| 264 |
-
-H "Content-Type: application/json" \\
|
| 265 |
-
-d '{"data": ["Tu texto aquí...", false]}'
|
| 266 |
-
```
|
| 267 |
-
|
| 268 |
-
## Hardware
|
| 269 |
-
|
| 270 |
-
Este Space funciona en **CPU básico** de Hugging Face (gratis). El modelo es lo suficientemente pequeño para ejecutarse eficientemente sin GPU.
|
| 271 |
-
|
| 272 |
-
## Licencia
|
| 273 |
|
| 274 |
MIT License
|
| 275 |
'''
|
| 276 |
|
| 277 |
with open('README.md', 'w', encoding='utf-8') as f:
|
| 278 |
-
f.write(
|
| 279 |
-
|
| 280 |
-
print("✅ Archivo README.md creado")
|
| 281 |
|
| 282 |
-
print("
|
| 283 |
-
print("
|
| 284 |
-
print("
|
| 285 |
-
print("
|
| 286 |
-
print("
|
| 287 |
-
print("✅ README.md - Documentación completa")
|
| 288 |
-
print("\n" + "="*60)
|
| 289 |
-
print("📋 PRÓXIMOS PASOS:")
|
| 290 |
-
print("="*60)
|
| 291 |
-
print("1. Crea un nuevo Space en https://huggingface.co/new-space")
|
| 292 |
-
print("2. Selecciona 'Gradio' como SDK")
|
| 293 |
-
print("3. Sube estos 3 archivos a tu Space")
|
| 294 |
-
print("4. Ve a Settings → Repository secrets")
|
| 295 |
-
print("5. Añade HF_TOKEN con tu token de Hugging Face")
|
| 296 |
-
print("6. ¡El Space se construirá automáticamente!")
|
| 297 |
-
print("="*60)
|
|
|
|
| 1 |
|
| 2 |
+
# Crear el código completo para un espacio de Hugging Face que genera títulos
|
| 3 |
+
# usando Llama-3.2-1B-Instruct con interfaz Gradio y API
|
| 4 |
|
| 5 |
+
app_code = '''import gradio as gr
|
| 6 |
+
import os
|
| 7 |
+
from huggingface_hub import InferenceClient
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
# Obtener el token de HF desde los secrets
|
| 10 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 11 |
|
| 12 |
+
# Inicializar el cliente de inferencia con el modelo Llama
|
| 13 |
+
client = InferenceClient(
|
| 14 |
+
model="meta-llama/Llama-3.2-1B-Instruct",
|
| 15 |
+
token=HF_TOKEN
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
)
|
|
|
|
| 17 |
|
| 18 |
+
def generate_title(text_or_history, max_length=50):
|
| 19 |
"""
|
| 20 |
+
Genera un título a partir de texto o historial de conversación
|
| 21 |
|
| 22 |
Args:
|
| 23 |
+
text_or_history: Puede ser texto simple o una lista de mensajes
|
| 24 |
+
max_length: Longitud máxima del título
|
| 25 |
|
| 26 |
Returns:
|
| 27 |
+
El título generado
|
| 28 |
"""
|
| 29 |
try:
|
| 30 |
+
# Si es una lista (historial), convertirla a texto
|
| 31 |
+
if isinstance(text_or_history, list):
|
| 32 |
+
# Formatear el historial como conversación
|
| 33 |
+
conversation_text = "\\n".join([
|
| 34 |
+
f"{msg.get('role', 'user')}: {msg.get('content', '')}"
|
| 35 |
+
for msg in text_or_history
|
| 36 |
+
])
|
| 37 |
else:
|
| 38 |
+
conversation_text = str(text_or_history)
|
|
|
|
| 39 |
|
| 40 |
+
# Crear el prompt para generar título
|
| 41 |
+
prompt = f"""Based on the following conversation or text, generate a short, concise title (maximum 10 words):
|
| 42 |
+
|
| 43 |
+
{conversation_text}
|
| 44 |
+
|
| 45 |
+
Title:"""
|
| 46 |
+
|
| 47 |
+
# Generar el título usando el modelo
|
| 48 |
messages = [
|
| 49 |
+
{"role": "user", "content": prompt}
|
|
|
|
| 50 |
]
|
| 51 |
|
| 52 |
+
response = ""
|
| 53 |
+
for message in client.chat_completion(
|
| 54 |
+
messages=messages,
|
| 55 |
+
max_tokens=max_length,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
temperature=0.7,
|
| 57 |
+
stream=True
|
| 58 |
+
):
|
| 59 |
+
token = message.choices[0].delta.content
|
| 60 |
+
if token:
|
| 61 |
+
response += token
|
| 62 |
|
| 63 |
+
# Limpiar el título (quitar saltos de línea extra, etc.)
|
| 64 |
+
title = response.strip().split("\\n")[0]
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
return title
|
| 67 |
|
| 68 |
except Exception as e:
|
| 69 |
+
return f"Error: {str(e)}"
|
| 70 |
|
| 71 |
+
# Crear la interfaz de Gradio
|
| 72 |
+
with gr.Blocks(title="Title Generator with Llama 3.2") as demo:
|
| 73 |
+
gr.Markdown("# 📝 AI Title Generator")
|
| 74 |
+
gr.Markdown("Generate concise titles from text or conversation history using Llama 3.2-1B-Instruct")
|
| 75 |
|
| 76 |
+
with gr.Tab("Text Input"):
|
| 77 |
+
text_input = gr.Textbox(
|
| 78 |
+
label="Enter your text",
|
| 79 |
+
placeholder="Paste your text or conversation here...",
|
| 80 |
+
lines=10
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
)
|
| 82 |
+
text_button = gr.Button("Generate Title", variant="primary")
|
| 83 |
+
text_output = gr.Textbox(label="Generated Title", lines=2)
|
| 84 |
|
| 85 |
+
text_button.click(
|
| 86 |
+
fn=generate_title,
|
| 87 |
+
inputs=[text_input],
|
| 88 |
+
outputs=[text_output]
|
|
|
|
|
|
|
| 89 |
)
|
| 90 |
|
| 91 |
+
with gr.Tab("History/List Input"):
|
| 92 |
+
gr.Markdown("Enter conversation history as JSON format:")
|
| 93 |
+
gr.Markdown('Example: `[{"role": "user", "content": "Hello"}, {"role": "assistant", "content": "Hi there!"}]`')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
+
history_input = gr.Textbox(
|
| 96 |
+
label="Conversation History (JSON)",
|
| 97 |
+
placeholder='[{"role": "user", "content": "Your message here"}]',
|
| 98 |
+
lines=10
|
| 99 |
)
|
| 100 |
+
history_button = gr.Button("Generate Title", variant="primary")
|
| 101 |
+
history_output = gr.Textbox(label="Generated Title", lines=2)
|
| 102 |
|
| 103 |
+
def process_history(history_json):
|
| 104 |
+
try:
|
| 105 |
+
import json
|
| 106 |
+
history_list = json.loads(history_json)
|
| 107 |
+
return generate_title(history_list)
|
| 108 |
+
except json.JSONDecodeError:
|
| 109 |
+
return "Error: Invalid JSON format"
|
| 110 |
+
|
| 111 |
+
history_button.click(
|
| 112 |
+
fn=process_history,
|
| 113 |
+
inputs=[history_input],
|
| 114 |
+
outputs=[history_output]
|
| 115 |
)
|
| 116 |
|
| 117 |
+
gr.Markdown("---")
|
| 118 |
+
gr.Markdown("### API Usage")
|
| 119 |
gr.Markdown("""
|
| 120 |
+
You can use this API with CURL:
|
| 121 |
+
|
| 122 |
+
```bash
|
| 123 |
+
curl -X POST "https://YOUR-SPACE-URL/call/generate_title" \\
|
| 124 |
+
-H "Content-Type: application/json" \\
|
| 125 |
+
-d '{"data": ["Your text here"]}'
|
| 126 |
+
```
|
| 127 |
""")
|
| 128 |
|
| 129 |
+
# Lanzar la aplicación con API habilitada
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
if __name__ == "__main__":
|
| 131 |
+
demo.launch(show_api=True)
|
| 132 |
'''
|
| 133 |
|
| 134 |
+
# Guardar el código en un archivo
|
| 135 |
with open('app.py', 'w', encoding='utf-8') as f:
|
| 136 |
+
f.write(app_code)
|
| 137 |
|
| 138 |
+
# Crear el archivo requirements.txt
|
| 139 |
+
requirements = '''gradio>=4.0.0
|
| 140 |
+
huggingface_hub>=0.19.0
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
'''
|
| 142 |
|
| 143 |
with open('requirements.txt', 'w', encoding='utf-8') as f:
|
| 144 |
+
f.write(requirements)
|
|
|
|
|
|
|
| 145 |
|
| 146 |
+
# Crear el README con instrucciones
|
| 147 |
+
readme = '''---
|
| 148 |
+
title: Title Generator with Llama 3.2
|
| 149 |
+
emoji: 📝
|
| 150 |
colorFrom: blue
|
| 151 |
colorTo: purple
|
| 152 |
sdk: gradio
|
| 153 |
+
sdk_version: 4.44.0
|
| 154 |
app_file: app.py
|
| 155 |
pinned: false
|
| 156 |
license: mit
|
| 157 |
---
|
| 158 |
|
| 159 |
+
# Title Generator with Llama 3.2-1B-Instruct
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
|
| 161 |
+
Generate concise titles from text or conversation history using Meta's Llama 3.2-1B-Instruct model.
|
| 162 |
|
| 163 |
+
## Features
|
|
|
|
|
|
|
| 164 |
|
| 165 |
+
- 📝 Generate titles from plain text
|
| 166 |
+
- 💬 Generate titles from conversation history
|
| 167 |
+
- 🚀 Fast inference with Llama 3.2-1B
|
| 168 |
+
- 🔌 RESTful API support for integration
|
| 169 |
|
| 170 |
+
## Setup
|
| 171 |
|
| 172 |
+
1. Go to your Space settings
|
| 173 |
+
2. Add a new secret: `HF_TOKEN` with your Hugging Face token
|
| 174 |
+
3. Make sure you have access to `meta-llama/Llama-3.2-1B-Instruct` (accept the gated model)
|
|
|
|
|
|
|
|
|
|
| 175 |
|
| 176 |
+
## API Usage
|
| 177 |
|
| 178 |
+
### CURL Example
|
|
|
|
|
|
|
|
|
|
| 179 |
|
| 180 |
+
```bash
|
| 181 |
+
curl -X POST "https://YOUR-SPACE-URL/call/generate_title" \\
|
| 182 |
+
-H "Content-Type: application/json" \\
|
| 183 |
+
-d '{"data": ["Your text or conversation here"]}'
|
| 184 |
+
```
|
|
|
|
|
|
|
| 185 |
|
| 186 |
+
### Python Example
|
| 187 |
|
| 188 |
```python
|
| 189 |
from gradio_client import Client
|
| 190 |
|
| 191 |
+
client = Client("YOUR-SPACE-URL")
|
| 192 |
+
result = client.predict("Your text here", api_name="/generate_title")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
print(result)
|
| 194 |
```
|
| 195 |
|
| 196 |
+
## License
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
|
| 198 |
MIT License
|
| 199 |
'''
|
| 200 |
|
| 201 |
with open('README.md', 'w', encoding='utf-8') as f:
|
| 202 |
+
f.write(readme)
|
|
|
|
|
|
|
| 203 |
|
| 204 |
+
print("✅ Archivos generados exitosamente:")
|
| 205 |
+
print("- app.py")
|
| 206 |
+
print("- requirements.txt")
|
| 207 |
+
print("- README.md")
|
| 208 |
+
print("\n📦 Archivos listos para subir a Hugging Face Space")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|