Uhhy commited on
Commit
ceecd2b
1 Parent(s): 5276ced

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +158 -0
  2. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from pydantic import BaseModel
3
+ from llama_cpp import Llama
4
+ from concurrent.futures import ThreadPoolExecutor, as_completed
5
+ from tqdm import tqdm
6
+ import uvicorn
7
+ from dotenv import load_dotenv
8
+ from difflib import SequenceMatcher
9
+ import re
10
+
11
+ # Cargar variables de entorno
12
+ load_dotenv()
13
+
14
+ # Inicializar aplicación FastAPI
15
+ app = FastAPI()
16
+
17
+ # Diccionario global para almacenar los modelos
18
+ global_data = {
19
+ 'models': []
20
+ }
21
+
22
+ # Configuración de los modelos
23
+ model_configs = [
24
+ {"repo_id": "Ffftdtd5dtft/Qwen2-1.5B-Instruct-Q2_K-GGUF", "filename": "qwen2-1.5b-instruct-q2_k.gguf", "name": "Qwen2 1.5B Instruct"}
25
+ ]
26
+
27
+ # Clase para gestionar modelos
28
+ class ModelManager:
29
+ def __init__(self):
30
+ self.models = []
31
+
32
+ def load_model(self, model_config):
33
+ print(f"Cargando modelo: {model_config['name']}...")
34
+ return {"model": Llama.from_pretrained(repo_id=model_config['repo_id'], filename=model_config['filename']), "name": model_config['name']}
35
+
36
+ def load_all_models(self):
37
+ print("Iniciando carga de modelos...")
38
+ with ThreadPoolExecutor(max_workers=len(model_configs)) as executor:
39
+ futures = [executor.submit(self.load_model, config) for config in model_configs]
40
+ models = []
41
+ for future in tqdm(as_completed(futures), total=len(model_configs), desc="Cargando modelos", unit="modelo"):
42
+ try:
43
+ model = future.result()
44
+ models.append(model)
45
+ print(f"Modelo cargado exitosamente: {model['name']}")
46
+ except Exception as e:
47
+ print(f"Error al cargar el modelo: {e}")
48
+ print("Todos los modelos han sido cargados.")
49
+ return models
50
+
51
+ # Instanciar ModelManager y cargar modelos
52
+ model_manager = ModelManager()
53
+ global_data['models'] = model_manager.load_all_models()
54
+
55
+ # Modelo global para la solicitud de chat
56
+ class ChatRequest(BaseModel):
57
+ message: str
58
+ top_k: int = 50
59
+ top_p: float = 0.95
60
+ temperature: float = 0.7
61
+
62
+ # Función para generar respuestas de chat
63
+ def generate_chat_response(request, model_data):
64
+ try:
65
+ user_input = normalize_input(request.message)
66
+ llm = model_data['model']
67
+ response = llm.create_chat_completion(
68
+ messages=[{"role": "user", "content": user_input}],
69
+ top_k=request.top_k,
70
+ top_p=request.top_p,
71
+ temperature=request.temperature
72
+ )
73
+ reply = response['choices'][0]['message']['content']
74
+ return {"response": reply, "literal": user_input, "model_name": model_data['name']}
75
+ except Exception as e:
76
+ return {"response": f"Error: {str(e)}", "literal": user_input, "model_name": model_data['name']}
77
+
78
+ def normalize_input(input_text):
79
+ return input_text.strip()
80
+
81
+ def remove_duplicates(text):
82
+ text = re.sub(r'(Hello there, how are you\? \[/INST\]){2,}', 'Hello there, how are you? [/INST]', text)
83
+ text = re.sub(r'(How are you\? \[/INST\]){2,}', 'How are you? [/INST]', text)
84
+ text = text.replace('[/INST]', '')
85
+ lines = text.split('\n')
86
+ unique_lines = list(dict.fromkeys(lines))
87
+ return '\n'.join(unique_lines).strip()
88
+
89
+ def remove_repetitive_responses(responses):
90
+ seen = set()
91
+ unique_responses = []
92
+ for response in responses:
93
+ normalized_response = remove_duplicates(response['response'])
94
+ if normalized_response not in seen:
95
+ seen.add(normalized_response)
96
+ unique_responses.append(response)
97
+ return unique_responses
98
+
99
+ def select_best_response(responses):
100
+ print("Filtrando respuestas...")
101
+ responses = remove_repetitive_responses(responses)
102
+ responses = [remove_duplicates(response['response']) for response in responses]
103
+ unique_responses = list(set(responses))
104
+ coherent_responses = filter_by_coherence(unique_responses)
105
+ best_response = filter_by_similarity(coherent_responses)
106
+ return best_response
107
+
108
+ def filter_by_coherence(responses):
109
+ print("Ordenando respuestas por coherencia...")
110
+ responses.sort(key=len, reverse=True)
111
+ return responses
112
+
113
+ def filter_by_similarity(responses):
114
+ print("Filtrando respuestas por similitud...")
115
+ responses.sort(key=len, reverse=True)
116
+ best_response = responses[0]
117
+ for i in range(1, len(responses)):
118
+ ratio = SequenceMatcher(None, best_response, responses[i]).ratio()
119
+ if ratio < 0.9:
120
+ best_response = responses[i]
121
+ break
122
+ return best_response
123
+
124
+ def worker_function(model_data, request):
125
+ print(f"Generando respuesta con el modelo: {model_data['name']}...")
126
+ response = generate_chat_response(request, model_data)
127
+ return response
128
+
129
+ @app.post("/generate_chat")
130
+ async def generate_chat(request: ChatRequest):
131
+ if not request.message.strip():
132
+ raise HTTPException(status_code=400, detail="The message cannot be empty.")
133
+
134
+ print(f"Procesando solicitud: {request.message}")
135
+
136
+ responses = []
137
+ num_models = len(global_data['models'])
138
+
139
+ with ThreadPoolExecutor(max_workers=num_models) as executor:
140
+ futures = [executor.submit(worker_function, model_data, request) for model_data in global_data['models']]
141
+ for future in tqdm(as_completed(futures), total=num_models, desc="Generando respuestas", unit="modelo"):
142
+ try:
143
+ response = future.result()
144
+ responses.append(response)
145
+ except Exception as exc:
146
+ print(f"Error en la generación de respuesta: {exc}")
147
+
148
+ best_response = select_best_response(responses)
149
+
150
+ print(f"Mejor respuesta seleccionada: {best_response}")
151
+
152
+ return {
153
+ "best_response": best_response,
154
+ "all_responses": responses
155
+ }
156
+
157
+ if __name__ == "__main__":
158
+ uvicorn.run(app, host="0.0.0.0", port=7860)
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ llama-cpp-python
4
+ python-dotenv
5
+ tqdm