Spaces:
Sleeping
Sleeping
File size: 6,487 Bytes
77c2378 9baac46 f4907db 9baac46 77c2378 9baac46 77c2378 9baac46 77c2378 9baac46 f4907db 9baac46 f4907db 77c2378 9baac46 77c2378 9baac46 77c2378 9baac46 77c2378 9baac46 77c2378 9baac46 77c2378 9baac46 f4907db 9baac46 77c2378 9baac46 77c2378 9baac46 f4907db 9baac46 77c2378 9baac46 77c2378 9baac46 77c2378 9baac46 f4907db 9baac46 77c2378 9baac46 77c2378 9baac46 77c2378 9baac46 77c2378 9baac46 77c2378 f4907db 9baac46 f4907db 9baac46 77c2378 9baac46 f4907db 9baac46 f4907db 9baac46 f4907db 9baac46 f4907db 9baac46 77c2378 9baac46 77c2378 9baac46 |
1 2 3 4 5 6 7 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 38 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 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 |
import os
import logging
import asyncio
import uvicorn
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from fastapi import FastAPI, Query, HTTPException
from fastapi.responses import HTMLResponse
# Configuraci贸n de logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# Inicializar la aplicaci贸n FastAPI
app = FastAPI()
# Diccionario para almacenar los modelos
data_and_models_dict = {}
# Lista para almacenar el historial de mensajes
message_history = []
# Funci贸n para cargar modelos
async def load_models():
gpt_models = ["gpt2-medium", "gpt2-large", "gpt2"]
for model_name in gpt_models:
try:
model = AutoModelForCausalLM.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
logger.info(f"Successfully loaded {model_name} model")
return model, tokenizer
except Exception as e:
logger.error(f"Failed to load GPT-2 model: {e}")
raise HTTPException(status_code=500, detail="Failed to load any models")
# Funci贸n para descargar modelos
async def download_models():
model, tokenizer = await load_models()
data_and_models_dict['model'] = (model, tokenizer)
@app.get('/')
async def main():
html_code = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ChatGPT Chatbot</title>
<style>
body, html {
height: 100%;
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}
.container {
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.chat-container {
border-radius: 10px;
overflow: hidden;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 100%;
height: 100%;
}
.chat-box {
height: calc(100% - 60px);
overflow-y: auto;
padding: 10px;
}
.chat-input {
width: calc(100% - 100px);
padding: 10px;
border: none;
border-top: 1px solid #ccc;
font-size: 16px;
}
.input-container {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px;
background-color: #f5f5f5;
border-top: 1px solid #ccc;
width: 100%;
}
button {
padding: 10px;
border: none;
cursor: pointer;
background-color: #007bff;
color: #fff;
font-size: 16px;
}
.user-message {
background-color: #cce5ff;
border-radius: 5px;
align-self: flex-end;
max-width: 70%;
margin-left: auto;
margin-right: 10px;
margin-bottom: 10px;
}
.bot-message {
background-color: #d1ecf1;
border-radius: 5px;
align-self: flex-start;
max-width: 70%;
margin-bottom: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="chat-container">
<div class="chat-box" id="chat-box"></div>
<div class="input-container">
<input type="text" class="chat-input" id="user-input" placeholder="Escribe un mensaje...">
<button onclick="sendMessage()">Enviar</button>
</div>
</div>
</div>
<script>
const chatBox = document.getElementById('chat-box');
const userInput = document.getElementById('user-input');
function saveMessage(sender, message) {
const messageElement = document.createElement('div');
messageElement.textContent = `${sender}: ${message}`;
messageElement.classList.add(`${sender}-message`);
chatBox.appendChild(messageElement);
userInput.value = '';
}
async function sendMessage() {
const userMessage = userInput.value.trim();
if (!userMessage) return;
saveMessage('user', userMessage);
await fetch(`/autocomplete?q=${userMessage}`)
.then(response => response.text())
.then(data => {
saveMessage('bot', data);
chatBox.scrollTop = chatBox.scrollHeight;
})
.catch(error => console.error('Error:', error));
}
userInput.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
sendMessage();
}
});
</script>
</body>
</html>
"""
return HTMLResponse(content=html_code, status_code=200)
# Ruta para la generaci贸n de respuestas
@app.get('/autocomplete')
async def autocomplete(q: str = Query(...)):
global data_and_models_dict, message_history
# Verificar si hay modelos cargados
if 'model' not in data_and_models_dict:
await download_models()
# Obtener el modelo
model, tokenizer = data_and_models_dict['model']
# Guardar el mensaje del usuario en el historial
message_history.append(q)
# Generar una respuesta utilizando el modelo
input_ids = tokenizer.encode(q, return_tensors="pt")
output = model.generate(input_ids, max_length=50, num_return_sequences=1)
response_text = tokenizer.decode(output[0], skip_special_tokens=True)
# Guardar la respuesta en el historial
message_history.append(response_text)
return response_text
# Funci贸n para ejecutar la aplicaci贸n sin reiniciarla
def run_app():
asyncio.run(download_models())
uvicorn.run(app, host='0.0.0.0', port=7860)
# Ejecutar la aplicaci贸n
if __name__ == "__main__":
run_app() |