Delta0723 commited on
Commit
2a847c9
·
verified ·
1 Parent(s): db0ce20

Upload simple_inference_api.py

Browse files
Files changed (1) hide show
  1. simple_inference_api.py +173 -0
simple_inference_api.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================
2
+ # app.py - Usando HF Inference API
3
+ # ============================================
4
+ import gradio as gr
5
+ import requests
6
+ import os
7
+
8
+ # Tu modelo ya está disponible en HF Inference API
9
+ MODEL_API = "https://api-inference.huggingface.co/models/Delta0723/techmind-pro-v9"
10
+ HF_TOKEN = os.getenv("HF_TOKEN", "") # Configura tu token en Settings del Space
11
+
12
+ def query_model(question, max_tokens=300, temperature=0.7):
13
+ if not HF_TOKEN:
14
+ return "❌ Error: Necesitas configurar tu HF_TOKEN en Settings > Repository secrets"
15
+
16
+ headers = {"Authorization": f"Bearer {HF_TOKEN}"}
17
+
18
+ payload = {
19
+ "inputs": f"<s>[INST] {question} [/INST]",
20
+ "parameters": {
21
+ "max_new_tokens": int(max_tokens),
22
+ "temperature": float(temperature),
23
+ "top_p": 0.95,
24
+ "do_sample": True,
25
+ "return_full_text": False
26
+ }
27
+ }
28
+
29
+ try:
30
+ response = requests.post(MODEL_API, headers=headers, json=payload, timeout=120)
31
+
32
+ if response.status_code == 503:
33
+ return "⏳ El modelo se está cargando en los servidores de HuggingFace. Espera 20 segundos e intenta de nuevo."
34
+
35
+ if response.status_code == 401:
36
+ return "❌ Error de autenticación. Verifica tu HF_TOKEN."
37
+
38
+ response.raise_for_status()
39
+ result = response.json()
40
+
41
+ if isinstance(result, list) and len(result) > 0:
42
+ return result[0].get("generated_text", "No response")
43
+
44
+ return str(result)
45
+
46
+ except requests.exceptions.RequestException as e:
47
+ return f"❌ Error: {str(e)}"
48
+
49
+ # Interfaz Gradio
50
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
51
+ gr.Markdown("""
52
+ # 🤖 TechMind Pro v9
53
+ ### Modelo basado en Mistral-7B + LoRA fine-tuning
54
+
55
+ *Usando HuggingFace Inference API (sin necesidad de GPU local)*
56
+ """)
57
+
58
+ with gr.Row():
59
+ with gr.Column(scale=1):
60
+ question_input = gr.Textbox(
61
+ label="💬 Tu Pregunta",
62
+ placeholder="Escribe tu pregunta aquí...",
63
+ lines=4
64
+ )
65
+
66
+ with gr.Accordion("⚙️ Parámetros Avanzados", open=False):
67
+ max_tokens_slider = gr.Slider(
68
+ minimum=50,
69
+ maximum=500,
70
+ value=300,
71
+ step=50,
72
+ label="Máximo de tokens"
73
+ )
74
+ temperature_slider = gr.Slider(
75
+ minimum=0.1,
76
+ maximum=1.0,
77
+ value=0.7,
78
+ step=0.1,
79
+ label="Temperatura (creatividad)"
80
+ )
81
+
82
+ submit_btn = gr.Button("🚀 Generar Respuesta", variant="primary", size="lg")
83
+
84
+ gr.Markdown("""
85
+ ---
86
+ **Nota:** La primera petición puede tardar ~20s mientras el modelo se carga.
87
+ Las siguientes serán más rápidas.
88
+ """)
89
+
90
+ with gr.Column(scale=1):
91
+ output = gr.Textbox(
92
+ label="✨ Respuesta",
93
+ lines=12,
94
+ show_copy_button=True
95
+ )
96
+
97
+ # Ejemplos
98
+ gr.Examples(
99
+ examples=[
100
+ ["¿Qué es Python y para qué se usa?"],
101
+ ["Explícame qué es machine learning de forma simple"],
102
+ ["¿Cómo funciona una red neuronal?"],
103
+ ["Dame consejos para aprender programación"]
104
+ ],
105
+ inputs=question_input,
106
+ label="📝 Ejemplos"
107
+ )
108
+
109
+ submit_btn.click(
110
+ fn=query_model,
111
+ inputs=[question_input, max_tokens_slider, temperature_slider],
112
+ outputs=output
113
+ )
114
+
115
+ if __name__ == "__main__":
116
+ demo.launch(server_name="0.0.0.0", server_port=7860)
117
+
118
+
119
+ # ============================================
120
+ # requirements.txt
121
+ # ============================================
122
+ """
123
+ gradio>=4.0.0
124
+ requests>=2.31.0
125
+ """
126
+
127
+
128
+ # ============================================
129
+ # README.md
130
+ # ============================================
131
+ """
132
+ ---
133
+ title: TechMind Pro v9
134
+ emoji: 🤖
135
+ colorFrom: blue
136
+ colorTo: purple
137
+ sdk: gradio
138
+ sdk_version: 4.44.0
139
+ app_file: app.py
140
+ pinned: false
141
+ license: mit
142
+ ---
143
+
144
+ # 🤖 TechMind Pro v9
145
+
146
+ Interfaz web para el modelo TechMind Pro v9 (Mistral-7B + LoRA fine-tuning)
147
+
148
+ ## 🚀 Cómo usar
149
+
150
+ 1. **Configura tu token de HuggingFace:**
151
+ - Ve a Settings > Repository secrets
152
+ - Añade: `HF_TOKEN` = tu token de https://huggingface.co/settings/tokens
153
+
154
+ 2. **Haz tu pregunta** y presiona "Generar Respuesta"
155
+
156
+ ## ⚡ Ventajas
157
+
158
+ - ✅ No consume recursos del Space (usa Inference API)
159
+ - ✅ GPU automática en los servidores de HF
160
+ - ✅ Respuestas rápidas después de la primera carga
161
+ - ✅ Gratis dentro de los límites de HF
162
+
163
+ ## 📊 Modelo
164
+
165
+ - **Base:** mistralai/Mistral-7B-Instruct-v0.3
166
+ - **Adaptador:** Delta0723/techmind-pro-v9
167
+ - **Backend:** HuggingFace Inference API
168
+
169
+ ## 🔒 Límites
170
+
171
+ - ~30 requests/minuto en el tier gratuito
172
+ - Primera petición tarda ~20s (cold start)
173
+ """