messmerbox / app.py
loztcontrol's picture
Upload 3 files
c4e6c36 verified
import gradio as gr
import os
import requests
import random
# Variables de entorno necesarias
API_URL = os.getenv("API_URL")
OPENAI_API_KEYS = os.getenv("OPENAI_API_KEYS", "").split(',')
NUM_THREADS = int(os.getenv("NUM_THREADS", "1"))
# Verifica que las variables de entorno necesarias est茅n definidas
if not API_URL or not OPENAI_API_KEYS:
raise ValueError("API_URL y OPENAI_API_KEYS deben estar definidas en el entorno.")
# Funci贸n para manejar errores
def exception_handler(exception_type, exception, traceback):
print(f"{exception_type.__name__}: {exception}")
sys.excepthook = exception_handler
sys.tracebacklimit = 0
# Funci贸n que procesa bloques de c贸digo en Markdown para ser renderizado en HTML
def parse_codeblock(text):
lines = text.split("\n")
for i, line in enumerate(lines):
if "```" in line:
if line != "```":
lines[i] = f'<pre><code class="{lines[i][3:]}">'
else:
lines[i] = '</code></pre>'
else:
if i > 0:
lines[i] = "<br/>" + line.replace("<", "&lt;").replace(">", "&gt;")
return "\n".join(lines)
# Funci贸n principal que interact煤a con el modelo o API externa
def query_api(input_text):
headers = {"Authorization": f"Bearer {random.choice(OPENAI_API_KEYS)}"}
payload = {"input": input_text}
try:
response = requests.post(API_URL, json=payload, headers=headers)
if response.status_code == 200:
return response.json().get("output", "No response from API.")
else:
return f"Error: {response.status_code} - {response.text}"
except Exception as e:
return f"Excepci贸n en la consulta: {str(e)}"
# Interfaz de Gradio
def app_function(input_text):
# Llamada a la funci贸n que consulta la API
result = query_api(input_text)
return result
# Definir la interfaz de Gradio
interface = gr.Interface(fn=app_function, inputs="text", outputs="text",
title="Consulta a la API",
description="Introduce un texto para consultar la API.")
# Ejecutar la interfaz en Hugging Face
if __name__ == "__main__":
interface.launch()