notrito commited on
Commit
fa8efcb
verified
1 Parent(s): 787a43c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -0
app.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from model import BigramLanguageModel
4
+
5
+ # Cargar el modelo
6
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
7
+ checkpoint = torch.load('quijote_gpt.pth', map_location=device)
8
+
9
+ # Extraer configuraci贸n y vocabulario
10
+ config = checkpoint['config']
11
+ vocab = checkpoint['vocab']
12
+ stoi = vocab['stoi']
13
+ itos = vocab['itos']
14
+
15
+ # Funciones encode/decode
16
+ encode = lambda s: [stoi[c] for c in s]
17
+ decode = lambda l: ''.join([itos[i] for i in l])
18
+
19
+ # Crear modelo y cargar pesos
20
+ model = BigramLanguageModel(
21
+ vocab_size=vocab['vocab_size'],
22
+ n_embd=config['n_embd'],
23
+ block_size=config['block_size'],
24
+ n_head=config['n_head'],
25
+ n_layer=config['n_layer'],
26
+ dropout=config['dropout']
27
+ )
28
+ model.load_state_dict(checkpoint['model_state_dict'])
29
+ model.to(device)
30
+ model.eval()
31
+
32
+ # Funci贸n de generaci贸n
33
+ def generate_text(prompt, max_length, temperature):
34
+ if not prompt:
35
+ prompt = "En un lugar de"
36
+
37
+ # Codificar el prompt
38
+ context = torch.tensor([encode(prompt)], dtype=torch.long, device=device)
39
+
40
+ # Generar
41
+ with torch.no_grad():
42
+ generated = model.generate(context, max_new_tokens=max_length, temperature=temperature)
43
+
44
+ # Decodificar
45
+ output = decode(generated[0].tolist())
46
+ return output
47
+
48
+ # Interfaz Gradio
49
+ demo = gr.Interface(
50
+ fn=generate_text,
51
+ inputs=[
52
+ gr.Textbox(
53
+ label="Escribe el inicio de tu texto",
54
+ placeholder="En un lugar de la Mancha...",
55
+ lines=3
56
+ ),
57
+ gr.Slider(
58
+ minimum=50,
59
+ maximum=2000,
60
+ value=500,
61
+ step=50,
62
+ label="Longitud de la continuaci贸n (caracteres)"
63
+ ),
64
+ gr.Slider(
65
+ minimum=0.5,
66
+ maximum=1.5,
67
+ value=1.0,
68
+ step=0.1,
69
+ label="Temperatura (creatividad)",
70
+ info="M谩s bajo = m谩s coherente, M谩s alto = m谩s creativo"
71
+ )
72
+ ],
73
+ outputs=gr.Textbox(label="Texto Generado", lines=15),
74
+ title="馃幁 Generador de Texto al Estilo Quijote",
75
+ description="Escribe el inicio de una historia y el modelo continuar谩 al estilo cervantino",
76
+ examples=[
77
+ ["En un lugar de la Mancha", 400, 1.0],
78
+ ["Don Quijote, caballero de", 300, 0.8],
79
+ ["Sancho Panza dijo:", 350, 1.2],
80
+ ],
81
+ theme=gr.themes.Soft()
82
+ )
83
+
84
+ if __name__ == "__main__":
85
+ demo.launch()