Interfaz Gradio
Browse filesHe integrado una interfaz de Gradio directamente en tu aplicaci贸n Flask (`backend/app.py` ). Ahora, al ejecutar la aplicaci贸n (localmente o en Hugging Face), tendr谩s una interfaz web simple donde puedes pegar c贸digo C, ejecutarlo y ver la salida o los errores.
Los cambios realizados incluyen:
- A帽adidas las dependencias`gradio` y`requests` a`requirements.txt` .
- Modificado`app.py` para crear y montar la interfaz de Gradio, que llama internamente a tu endpoint`/api/execute` .
- Actualizado el`Dockerfile` para asegurar la instalaci贸n de las nuevas dependencias.
- Actualizados los archivos`README.md` (principal y del backend) para reflejar la nueva interfaz y simplificar las instrucciones de despliegue en Hugging Face.
- Dockerfile +1 -0
- README.md +1 -1
- app.py +67 -1
- requirements.txt +3 -1
Dockerfile
CHANGED
|
@@ -12,6 +12,7 @@ WORKDIR /app
|
|
| 12 |
COPY requirements.txt .
|
| 13 |
|
| 14 |
# Instalar dependencias de Python
|
|
|
|
| 15 |
RUN pip install --no-cache-dir -r requirements.txt
|
| 16 |
|
| 17 |
# Copiar el c贸digo de la aplicaci贸n
|
|
|
|
| 12 |
COPY requirements.txt .
|
| 13 |
|
| 14 |
# Instalar dependencias de Python
|
| 15 |
+
# Instalar dependencias de Python (incluyendo Gradio)
|
| 16 |
RUN pip install --no-cache-dir -r requirements.txt
|
| 17 |
|
| 18 |
# Copiar el c贸digo de la aplicaci贸n
|
README.md
CHANGED
|
@@ -117,7 +117,7 @@ Para desplegar este servicio en Hugging Face Spaces:
|
|
| 117 |
1. Crea un nuevo Space en Hugging Face
|
| 118 |
2. Selecciona Docker como tipo de espacio
|
| 119 |
3. Sube los archivos del backend (incluyendo el Dockerfile)
|
| 120 |
-
4.
|
| 121 |
|
| 122 |
## Licencia
|
| 123 |
|
|
|
|
| 117 |
1. Crea un nuevo Space en Hugging Face
|
| 118 |
2. Selecciona Docker como tipo de espacio
|
| 119 |
3. Sube los archivos del backend (incluyendo el Dockerfile)
|
| 120 |
+
4. 隆Listo! La interfaz de Gradio estar谩 disponible en la URL de tu Space.
|
| 121 |
|
| 122 |
## Licencia
|
| 123 |
|
app.py
CHANGED
|
@@ -6,6 +6,8 @@ import uuid
|
|
| 6 |
import time
|
| 7 |
import logging
|
| 8 |
from flask_cors import CORS
|
|
|
|
|
|
|
| 9 |
|
| 10 |
app = Flask(__name__)
|
| 11 |
CORS(app) # Habilitar CORS para todas las rutas
|
|
@@ -19,7 +21,22 @@ TEMP_DIR = os.path.join(tempfile.gettempdir(), '42coderunner')
|
|
| 19 |
os.makedirs(TEMP_DIR, exist_ok=True)
|
| 20 |
|
| 21 |
# Tiempo m谩ximo de ejecuci贸n (en segundos)
|
| 22 |
-
MAX_EXECUTION_TIME =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
@app.route('/api/execute', methods=['POST'])
|
| 25 |
def execute_code():
|
|
@@ -105,6 +122,55 @@ def health_check():
|
|
| 105 |
# The previous checks (compiler, temp dir) might fail in the HF environment
|
| 106 |
return jsonify({'status': 'ok', 'timestamp': time.time()})
|
| 107 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
if __name__ == '__main__':
|
| 109 |
port = int(os.environ.get('PORT', 5000))
|
| 110 |
app.run(host='0.0.0.0', port=port)
|
|
|
|
| 6 |
import time
|
| 7 |
import logging
|
| 8 |
from flask_cors import CORS
|
| 9 |
+
import gradio as gr
|
| 10 |
+
import requests
|
| 11 |
|
| 12 |
app = Flask(__name__)
|
| 13 |
CORS(app) # Habilitar CORS para todas las rutas
|
|
|
|
| 21 |
os.makedirs(TEMP_DIR, exist_ok=True)
|
| 22 |
|
| 23 |
# Tiempo m谩ximo de ejecuci贸n (en segundos)
|
| 24 |
+
MAX_EXECUTION_TIME = 10 # Aumentamos un poco para Gradio
|
| 25 |
+
|
| 26 |
+
# URL base de la API (para la interfaz Gradio)
|
| 27 |
+
# Detecta si estamos en Hugging Face Spaces
|
| 28 |
+
API_BASE_URL = os.environ.get("SPACE_HOST")
|
| 29 |
+
if API_BASE_URL:
|
| 30 |
+
# En Hugging Face, usa la URL p煤blica del espacio
|
| 31 |
+
# Aseg煤rate de que el protocolo sea https
|
| 32 |
+
API_BASE_URL = f"https://{API_BASE_URL}"
|
| 33 |
+
else:
|
| 34 |
+
# Localmente, usa localhost
|
| 35 |
+
API_BASE_URL = "http://localhost:5000"
|
| 36 |
+
|
| 37 |
+
API_EXECUTE_URL = f"{API_BASE_URL}/api/execute"
|
| 38 |
+
|
| 39 |
+
# --- Funciones de la API Flask ---
|
| 40 |
|
| 41 |
@app.route('/api/execute', methods=['POST'])
|
| 42 |
def execute_code():
|
|
|
|
| 122 |
# The previous checks (compiler, temp dir) might fail in the HF environment
|
| 123 |
return jsonify({'status': 'ok', 'timestamp': time.time()})
|
| 124 |
|
| 125 |
+
# --- Interfaz Gradio ---
|
| 126 |
+
|
| 127 |
+
def run_c_code(c_code):
|
| 128 |
+
"""Funci贸n que se ejecuta cuando el usuario env铆a c贸digo C a trav茅s de Gradio."""
|
| 129 |
+
logger.info(f"Solicitud Gradio recibida. URL API: {API_EXECUTE_URL}")
|
| 130 |
+
try:
|
| 131 |
+
response = requests.post(API_EXECUTE_URL, json={'code': c_code}, timeout=MAX_EXECUTION_TIME + 5) # Timeout un poco mayor para la request
|
| 132 |
+
response.raise_for_status() # Lanza excepci贸n para errores HTTP
|
| 133 |
+
data = response.json()
|
| 134 |
+
|
| 135 |
+
if data.get('success'):
|
| 136 |
+
output = f"--- Salida ({data.get('execution_time', 0):.4f}s) ---\n{data.get('output', '')}"
|
| 137 |
+
if data.get('error'): # Mostrar stderr aunque la ejecuci贸n sea exitosa (warnings, etc.)
|
| 138 |
+
output += f"\n\n--- Errores (stderr) ---\n{data['error']}"
|
| 139 |
+
return output
|
| 140 |
+
else:
|
| 141 |
+
return f"--- Error ---\n{data.get('error', 'Error desconocido')}"
|
| 142 |
+
|
| 143 |
+
except requests.exceptions.RequestException as e:
|
| 144 |
+
logger.error(f"Error de red al llamar a la API: {e}")
|
| 145 |
+
return f"Error de red al conectar con el backend: {e}"
|
| 146 |
+
except Exception as e:
|
| 147 |
+
logger.error(f"Error inesperado en la interfaz Gradio: {e}")
|
| 148 |
+
return f"Error inesperado en la interfaz: {str(e)}"
|
| 149 |
+
|
| 150 |
+
# Ejemplo de c贸digo C para la interfaz
|
| 151 |
+
EXAMPLE_CODE = """#include <stdio.h>
|
| 152 |
+
|
| 153 |
+
int main() {
|
| 154 |
+
printf("隆Hola desde 42CodeRunner!\n");
|
| 155 |
+
return 0;
|
| 156 |
+
}
|
| 157 |
+
"""
|
| 158 |
+
|
| 159 |
+
# Crear la interfaz Gradio
|
| 160 |
+
iface = gr.Interface(
|
| 161 |
+
fn=run_c_code,
|
| 162 |
+
inputs=gr.Code(language="c", label="C贸digo C", value=EXAMPLE_CODE),
|
| 163 |
+
outputs=gr.Textbox(label="Resultado de la Ejecuci贸n", lines=15),
|
| 164 |
+
title="馃強u200d鈾傦笍 42CodeRunner",
|
| 165 |
+
description="Escribe tu c贸digo C, haz clic en 'Submit' y mira la magia suceder. Ejecutado de forma segura en el backend.",
|
| 166 |
+
allow_flagging='never'
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
# Montar la interfaz Gradio en la app Flask en la ruta ra铆z
|
| 170 |
+
app = gr.mount_gradio_app(app, iface, path="/")
|
| 171 |
+
|
| 172 |
+
# --- Ejecuci贸n de la App ---
|
| 173 |
+
|
| 174 |
if __name__ == '__main__':
|
| 175 |
port = int(os.environ.get('PORT', 5000))
|
| 176 |
app.run(host='0.0.0.0', port=port)
|
requirements.txt
CHANGED
|
@@ -1,5 +1,7 @@
|
|
| 1 |
flask==2.0.1
|
| 2 |
-
|
|
|
|
|
|
|
| 3 |
gunicorn==20.1.0
|
| 4 |
python-dotenv==0.19.0
|
| 5 |
werkzeug==2.0.1
|
|
|
|
| 1 |
flask==2.0.1
|
| 2 |
+
Flask-Cors
|
| 3 |
+
gradio
|
| 4 |
+
requests
|
| 5 |
gunicorn==20.1.0
|
| 6 |
python-dotenv==0.19.0
|
| 7 |
werkzeug==2.0.1
|