Spaces:
Sleeping
Sleeping
Commit
路
7e075b9
1
Parent(s):
5fe321d
Reemplazo de app.py
Browse files
app.py
CHANGED
|
@@ -1,126 +1,115 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
import requests
|
| 3 |
-
import logging
|
| 4 |
-
import os
|
| 5 |
-
from fastapi import FastAPI, Request
|
| 6 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 7 |
-
import uvicorn
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
response
|
| 38 |
-
response.
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
"
|
| 54 |
-
|
| 55 |
-
"
|
| 56 |
-
"
|
| 57 |
-
"
|
| 58 |
-
"
|
| 59 |
-
"
|
| 60 |
-
"
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
"
|
| 81 |
-
"
|
| 82 |
-
"
|
| 83 |
-
"
|
| 84 |
-
"
|
| 85 |
-
"
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
resolucion_mejorada
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
#
|
| 114 |
-
|
| 115 |
-
uvicorn.run(app, host="0.0.0.0", port=7860)
|
| 116 |
-
|
| 117 |
-
# Ejecutar Gradio y FastAPI en procesos separados
|
| 118 |
-
if __name__ == "__main__":
|
| 119 |
-
gradio_process = Process(target=run_gradio)
|
| 120 |
-
fastapi_process = Process(target=run_fastapi)
|
| 121 |
-
|
| 122 |
-
gradio_process.start()
|
| 123 |
-
fastapi_process.start()
|
| 124 |
-
|
| 125 |
-
gradio_process.join()
|
| 126 |
-
fastapi_process.join()
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import requests
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
from fastapi import FastAPI, Request
|
| 6 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 7 |
+
import uvicorn
|
| 8 |
+
|
| 9 |
+
# Crear la aplicaci贸n FastAPI
|
| 10 |
+
app = FastAPI()
|
| 11 |
+
|
| 12 |
+
# Configurar CORS si es necesario
|
| 13 |
+
app.add_middleware(
|
| 14 |
+
CORSMiddleware,
|
| 15 |
+
allow_origins=["*"], # Ajusta esto seg煤n tus necesidades
|
| 16 |
+
allow_credentials=True,
|
| 17 |
+
allow_methods=["*"],
|
| 18 |
+
allow_headers=["*"],
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
# Leer el token de Hugging Face desde las variables de entorno
|
| 22 |
+
HUGGING_FACE_TOKEN = os.getenv("HUGGING_FACE_TOKEN")
|
| 23 |
+
API_URL = "https://api-inference.huggingface.co/models/meta-llama/Meta-Llama-3-70B-Instruct"
|
| 24 |
+
|
| 25 |
+
if not HUGGING_FACE_TOKEN:
|
| 26 |
+
raise ValueError("El token de Hugging Face no est谩 configurado en las variables de entorno")
|
| 27 |
+
|
| 28 |
+
headers = {"Authorization": f"Bearer {HUGGING_FACE_TOKEN}"}
|
| 29 |
+
|
| 30 |
+
# Configurar el logger
|
| 31 |
+
logging.basicConfig(filename='interactions.log', level=logging.INFO,
|
| 32 |
+
format='%(asctime)s - %(levelname)s - %(message)s')
|
| 33 |
+
|
| 34 |
+
def query(api_url, headers, payload):
|
| 35 |
+
try:
|
| 36 |
+
response = requests.post(api_url, headers=headers, json=payload)
|
| 37 |
+
response.raise_for_status()
|
| 38 |
+
return response.json()
|
| 39 |
+
except requests.exceptions.RequestException as e:
|
| 40 |
+
error_message = f"Error durante la solicitud: {e}"
|
| 41 |
+
if e.response:
|
| 42 |
+
error_message += f" C贸digo de estado: {e.response.status_code} Respuesta del servidor: {e.response.text}"
|
| 43 |
+
logging.error(error_message)
|
| 44 |
+
return {"error": error_message}
|
| 45 |
+
|
| 46 |
+
def preparar_texto(contexto, borrador):
|
| 47 |
+
return f"{contexto}\n\n{borrador}"
|
| 48 |
+
|
| 49 |
+
def mejorar_resolucion(context, borrador, api_url, headers, max_length=1000):
|
| 50 |
+
prompt = preparar_texto(context, borrador)
|
| 51 |
+
payload = {
|
| 52 |
+
"inputs": prompt,
|
| 53 |
+
"parameters": {
|
| 54 |
+
"max_new_tokens": max_length,
|
| 55 |
+
"temperature": 0.7,
|
| 56 |
+
"top_p": 0.9,
|
| 57 |
+
"top_k": 50,
|
| 58 |
+
"repetition_penalty": 1.2,
|
| 59 |
+
"return_full_text": False,
|
| 60 |
+
"do_sample": True,
|
| 61 |
+
}
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
result = query(api_url, headers, payload)
|
| 65 |
+
|
| 66 |
+
if result and isinstance(result, list) and 'generated_text' in result[0]:
|
| 67 |
+
texto_generado = result[0]['generated_text']
|
| 68 |
+
context += f"\n\n{texto_generado}"
|
| 69 |
+
logging.info(f"Prompt: {prompt}\nGenerated: {texto_generado.strip()}")
|
| 70 |
+
return texto_generado.strip(), context
|
| 71 |
+
else:
|
| 72 |
+
error_message = result.get("error", "No se pudo obtener la respuesta del modelo.")
|
| 73 |
+
logging.error(f"Prompt: {prompt}\nError: {error_message}")
|
| 74 |
+
return None, context
|
| 75 |
+
|
| 76 |
+
# Funci贸n de predicci贸n para la interfaz de Gradio
|
| 77 |
+
def predict(message, history):
|
| 78 |
+
context = (
|
| 79 |
+
"Asume el papel de asistente legal especializado en derecho chileno. Tu meta es optimizar resoluciones judiciales utilizando procesamiento de lenguaje natural (PLN). "
|
| 80 |
+
"Mant茅n un tono formal, preciso y autoritativo en todo momento. Como requierase, autoricese, apercibase, entre otros. "
|
| 81 |
+
"Sigue estrictamente las gu铆as de estilo proporcionadas. Simplifica oraciones complejas y elimina redundancias. Adapta la terminolog铆a al contexto legal chileno. "
|
| 82 |
+
"Aseg煤rate de que las resoluciones optimizadas sean claras, concisas y libres de ambig眉edades. Utiliza par谩frasis, analog铆as y ejemplos para mejorar la claridad. "
|
| 83 |
+
"Revisa documentos de referencia. Identifica inconsistencias, ambig眉edades y redundancias. Simplifica oraciones complejas y elimina redundancias. "
|
| 84 |
+
"Realiza una revisi贸n gramatical y estil铆stica para asegurar precisi贸n y formalidad. Justifica las modificaciones necesarias. Explica c贸mo cada mejora contribuye a la formalidad, precisi贸n y claridad. "
|
| 85 |
+
"Proporciona la Resoluci贸n Optimizada. Verifica que la resoluci贸n optimizada cumpla con los criterios de claridad, precisi贸n y formalidad. Asegura que todas las modificaciones est茅n justificadas y sean comprensibles."
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
history_transformer_format = history + [[message, ""]]
|
| 89 |
+
for item in history_transformer_format:
|
| 90 |
+
context += f"\n\n{item[0]}"
|
| 91 |
+
|
| 92 |
+
resolucion_mejorada, context = mejorar_resolucion(context, message, API_URL, headers, max_length=1000)
|
| 93 |
+
if resolucion_mejorada:
|
| 94 |
+
history.append([message, resolucion_mejorada])
|
| 95 |
+
return resolucion_mejorada
|
| 96 |
+
else:
|
| 97 |
+
return "No se pudo mejorar la resoluci贸n."
|
| 98 |
+
|
| 99 |
+
# Crear la interfaz de Gradio
|
| 100 |
+
iface = gr.ChatInterface(predict)
|
| 101 |
+
|
| 102 |
+
# Montar la aplicaci贸n de Gradio en FastAPI
|
| 103 |
+
app = gr.mount_gradio_app(app, iface, path="/gradio")
|
| 104 |
+
|
| 105 |
+
# Endpoint de FastAPI para la predicci贸n
|
| 106 |
+
@app.post("/predict")
|
| 107 |
+
async def api_predict(request: Request):
|
| 108 |
+
data = await request.json()
|
| 109 |
+
message = data.get("message")
|
| 110 |
+
response = predict(message, [])
|
| 111 |
+
return {"response": response}
|
| 112 |
+
|
| 113 |
+
# Ejecutar la aplicaci贸n FastAPI
|
| 114 |
+
if __name__ == "__main__":
|
| 115 |
+
uvicorn.run(app, host="0.0.0.0", port=7860, log_level="info")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|