TobDeBer commited on
Commit
53a8258
·
verified ·
1 Parent(s): 0942c27

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -142
app.py CHANGED
@@ -1,7 +1,9 @@
1
  import spaces
2
  import json
3
  import os
4
- import subprocess # Behalten wir, falls es für andere Dinge gebraucht wird, obwohl es hier nicht mehr direkt verwendet wird
 
 
5
  from llama_cpp import Llama
6
  from llama_cpp_agent import LlamaCppAgent, MessagesFormatterType
7
  from llama_cpp_agent.providers import LlamaCppPythonProvider
@@ -9,139 +11,19 @@ from llama_cpp_agent.chat_history import BasicChatHistory
9
  from llama_cpp_agent.chat_history.messages import Roles
10
  import gradio as gr
11
  from huggingface_hub import hf_hub_download, list_repo_files
 
12
 
13
  # --- Globale Konfiguration und Variablen ---
14
  llm = None
15
  llm_model = None
16
- MODEL_CONFIG_FILE = "models.json"
17
- DEFAULT_LOCAL_DIR = "./models"
18
- MODEL_DROPDOWN_CHOICES = []
19
- # Map: Anzeigename -> Tatsächlicher Pfad zur ersten Modelldatei
20
- MODEL_FILE_MAPPING = {}
21
-
22
- # Stelle sicher, dass das models-Verzeichnis existiert
23
- os.makedirs(DEFAULT_LOCAL_DIR, exist_ok=True)
24
-
25
-
26
- # ----------------------------------------------------------------------
27
- ## Modell-Downloads und Konfigurations-Parsing
28
- # ----------------------------------------------------------------------
29
-
30
- def download_models():
31
- """Liest models.json, lädt Modelle herunter und füllt die globale Map."""
32
- global MODEL_DROPDOWN_CHOICES
33
- global MODEL_FILE_MAPPING
34
-
35
- try:
36
- with open(MODEL_CONFIG_FILE, 'r') as f:
37
- config = json.load(f)
38
- except FileNotFoundError:
39
- print(f"❌ FEHLER: Konfigurationsdatei '{MODEL_CONFIG_FILE}' nicht gefunden.")
40
- # Füge einen Platzhalter hinzu, falls die Datei fehlt
41
- MODEL_DROPDOWN_CHOICES.append("ERROR: models.json fehlt")
42
- return
43
- except json.JSONDecodeError as e:
44
- print(f"❌ FEHLER: {MODEL_CONFIG_FILE} ist kein gültiges JSON. Fehler: {e}")
45
- MODEL_DROPDOWN_CHOICES.append("ERROR: models.json ungültig")
46
- return
47
-
48
- # Holen des lokalen Zielverzeichnisses aus der JSON-Datei
49
- local_dir = config.get('local_dir', DEFAULT_LOCAL_DIR)
50
- if not os.path.exists(local_dir):
51
- os.makedirs(local_dir, exist_ok=True)
52
- print(f"Lokales Verzeichnis {local_dir} erstellt.")
53
-
54
- models_list = config.get('models', [])
55
-
56
- print(f"✨ Starte den Download von {len(models_list)} konfigurierten Modellen...")
57
-
58
- for model_entry in models_list:
59
- name = model_entry.get('name')
60
- repo_id = model_entry.get('repo_id')
61
- file_name = model_entry.get('file_name')
62
- folder_name = model_entry.get('folder_name')
63
 
64
- if not name or not repo_id:
65
- print(f"⚠️ WARNUNG: Eintrag ohne 'name' oder 'repo_id' übersprungen: {model_entry}")
66
- continue
67
-
68
- # Füge den Anzeigenamen zur Dropdown-Liste hinzu
69
- MODEL_DROPDOWN_CHOICES.append(name)
70
-
71
- # Fall 1: Einzelne Datei (file_name)
72
- if file_name:
73
- print(f" -> Lade Einzeldatei für '{name}': {file_name}")
74
- try:
75
- hf_hub_download(
76
- repo_id=repo_id,
77
- filename=file_name,
78
- local_dir=local_dir
79
- )
80
- # Den vollständigen Pfad speichern (relativ zum Installationsort)
81
- MODEL_FILE_MAPPING[name] = os.path.join(local_dir, file_name)
82
- print(f" -> Erfolgreich heruntergeladen: {name}")
83
- except Exception as e:
84
- print(f"❌ FEHLER beim Download von {name} ({file_name}): {e}")
85
-
86
- # Fall 2: Ganzer Ordner (folder_name)
87
- elif folder_name:
88
- print(f" -> Lade Ordner für '{name}': {folder_name}")
89
-
90
- try:
91
- all_files = list_repo_files(repo_id=repo_id)
92
- files_to_download = sorted([
93
- filename
94
- for filename in all_files
95
- if filename.startswith(f"{folder_name}/")
96
- ])
97
- except Exception as e:
98
- print(f"❌ FEHLER beim Auflisten der Dateien im Repo {repo_id}: {e}")
99
- continue
100
-
101
- if not files_to_download:
102
- print(f"⚠️ WARNUNG: Im Ordner '{folder_name}' wurden keine Dateien gefunden.")
103
- continue
104
-
105
- first_part_filename = files_to_download[0]
106
-
107
- # Jede Datei einzeln herunterladen
108
- for filename in files_to_download:
109
- print(f" - Download von {filename}")
110
- try:
111
- hf_hub_download(
112
- repo_id=repo_id,
113
- filename=filename,
114
- local_dir=local_dir
115
- )
116
- except Exception as e:
117
- print(f"❌ FEHLER beim Herunterladen von {filename}: {e}")
118
-
119
- # Für Llama-CPP-Initialisierung den Pfad zum ersten Teil speichern
120
- # Pfad: <local_dir>/<folder_name>/<first_file_part>
121
- MODEL_FILE_MAPPING[name] = os.path.join(local_dir, first_part_filename)
122
- print(f" -> Erfolgreich heruntergeladen: {name}. Erster Teil: {MODEL_FILE_MAPPING[name]}")
123
-
124
- else:
125
- print(f"⚠️ WARNUNG: Für '{name}' wurde weder 'file_name' noch 'folder_name' angegeben. Übersprungen.")
126
-
127
- print("--- Download-Vorgang abgeschlossen. ---")
128
-
129
- # --- Globale Downloads einmalig starten ---
130
- download_models()
131
- # ----------------------------------------
132
-
133
-
134
- # --- CSS Styling (Unverändert) ---
135
  css = """.bubble-wrap { padding-top: calc(var(--spacing-xl) * 3) !important;}.message-row { justify-content: space-evenly !important; width: 100% !important; max-width: 100% !important; margin: calc(var(--spacing-xl)) 0 !important; padding: 0 calc(var(--spacing-xl) * 3) !important;}.flex-wrap.user { border-bottom-right-radius: var(--radius-lg) !important;}.flex-wrap.bot { border-bottom-left-radius: var(--radius-lg) !important;}.message.user{ padding: 10px;}.message.bot{ text-align: right; width: 100%; padding: 10px; border-radius: 10px;}.message-bubble-border { border-radius: 6px !important;}.message-buttons { justify-content: flex-end !important;}.message-buttons-left { align-self: end !important;}.message-buttons-bot, .message-buttons-user { right: 10px !important; left: auto !important; bottom: 2px !important;}.dark.message-bubble-border { border-color: #343140 !important;}.dark.user { background: #1e1c26 !important;}.dark.assistant.dark, .dark.pending.dark { background: #16141c !important;}"""
136
 
137
- # --- Hilfsfunktion für den Message Formatter Typ (Unverändert) ---
138
  def get_messages_formatter_type(model_name):
139
- # Nutzt jetzt den Anzeigenamen
140
  if "Llama" in model_name:
141
  return MessagesFormatterType.LLAMA_3
142
  elif "Mistral" in model_name:
143
  return MessagesFormatterType.MISTRAL
144
- # Das ist eine gute Annahme für die meisten unsloth-Modelle, wenn kein spezifischer Typ bekannt ist
145
  elif "GLM" in model_name or "Granite" in model_name:
146
  return MessagesFormatterType.CHATML
147
  else:
@@ -149,7 +31,7 @@ def get_messages_formatter_type(model_name):
149
  return MessagesFormatterType.CHATML
150
 
151
  # ----------------------------------------------------------------------
152
- ## Haupt-Antwortfunktion für ChatInterface
153
  # ----------------------------------------------------------------------
154
 
155
  @spaces.GPU(duration=45)
@@ -167,17 +49,15 @@ def respond(
167
  global llm
168
  global llm_model
169
 
170
- # 1. Den tatsächlichen Dateipfad über das Mapping abrufen
171
  model_file_path = MODEL_FILE_MAPPING.get(selected_model_name)
172
 
173
  if not model_file_path:
174
- return f"Fehler: Model-Datei für '{selected_model_name}' nicht gefunden. Ist der Download fehlgeschlagen?"
175
 
176
  chat_template = get_messages_formatter_type(selected_model_name)
177
 
178
- # 2. Llama-Objekt nur neu initialisieren, wenn nötig
179
  if llm is None or llm_model != model_file_path:
180
- print(f"Lade neues Modell: {model_file_path}")
181
  try:
182
  llm = Llama(
183
  model_path=model_file_path,
@@ -188,9 +68,8 @@ def respond(
188
  )
189
  llm_model = model_file_path
190
  except Exception as e:
191
- return f"Fehler beim Laden von Llama-Modell '{selected_model_name}' ({model_file_path}): {e}"
192
 
193
- # 3. Agent initialisieren und Einstellungen setzen
194
  provider = LlamaCppPythonProvider(llm)
195
  agent = LlamaCppAgent(
196
  provider,
@@ -207,13 +86,11 @@ def respond(
207
  settings.repeat_penalty = repeat_penalty
208
  settings.stream = True
209
 
210
- # 4. Chat-Verlauf vorbereiten
211
  messages = BasicChatHistory()
212
  for msn in history:
213
  role = Roles.user if msn.get('role') == 'user' else Roles.assistant
214
  messages.add_message({'role': role, 'content': msn.get('content', '')})
215
 
216
- # 5. Stream-Antwort generieren
217
  stream = agent.get_chat_response(
218
  message,
219
  llm_sampling_settings=settings,
@@ -227,13 +104,9 @@ def respond(
227
  outputs += output
228
  yield outputs
229
 
230
- # --- HTML Platzhalter für den Chatbot (Unverändert) ---
231
- PLACEHOLDER = """<div class="message-bubble-border" style="display:flex; max-width: 600px; border-radius: 6px; border-width: 1px; border-color: #e5e7eb; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); backdrop-filter: blur(10px);"> <div style="padding: .5rem 1.5rem;display: flex;flex-direction: column;justify-content: space-evenly;"> <h2 style="text-align: left; font-size: 1.5rem; font-weight: 700; margin-bottom: 0.5rem;">llama-cpp-agent</h2> <p style="text-align: left; font-size: 16px; line-height: 1.5; margin-bottom: 15px;">The llama-cpp-agent framework based on llama_cpp_python simplifies interactions with Large Language Models (LLMs). Here you can try out a range of models via the basic chat interface. For advanced features check out the discord or github link below.</p> <div style="display: flex; justify-content: space-between; align-items: center;"> <div style="display: flex; justify-content: flex-end; align-items: center;"> <a href="https://discord.gg/fgr5RycPFP" target="_blank" rel="noreferrer" style="padding: .5rem;"> <svg width="24" height="24" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 5 30.67 23.25"> <title>Discord</title> <path d="M26.0015 6.9529C24.0021 6.03845 21.8787 5.37198 19.6623 5C19.3833 5.48048 19.0733 6.13144 18.8563 6.64292C16.4989 6.30193 14.1585 6.30193 11.8336 6.64292C11.6166 6.13144 11.2911 5.48048 11.0276 5C8.79575 5.37198 6.67235 6.03845 4.6869 6.9529C0.672601 12.8736 -0.41235 18.6548 0.130124 24.3585C2.79599 26.2959 5.36889 27.4739 7.89682 28.2489C8.51679 27.4119 9.07477 26.5129 9.55525 25.5675C8.64079 25.2265 7.77283 24.808 6.93587 24.312C7.15286 24.1571 7.36986 23.9866 7.57135 23.8161C12.6241 26.1255 18.0969 26.1255 23.0876 23.8161C23.3046 23.9866 23.5061 24.1571 23.7231 24.312C22.8861 24.808 22.0182 25.2265 21.1037 25.5675C21.5842 26.5129 22.1422 27.4119 22.7621 28.2489C25.2885 27.4739 27.8769 26.2959 30.5288 24.3585C31.1952 17.7559 29.4733 12.0212 26.0015 6.9529ZM10.2527 20.8402C8.73376 20.8402 7.49382 19.4608 7.49382 17.7714C7.49382 16.082 8.70276 14.7025 10.2527 14.7025C11.7871 14.7025 13.0425 16.082 13.0115 17.7714C13.0115 19.4608 11.7871 20.8402 10.2527 20.8402ZM20.4373 20.8402C18.9183 20.8402 17.6768 19.4608 17.6768 17.7714C17.6768 16.082 18.8873 14.7025 20.4373 14.7025C21.9717 14.7025 23.2271 16.082 23.1961 17.7714C23.1961 19.4608 21.9872 20.8402 20.4373 20.8402Z"></path> </svg> </a> <a href="https://github.com/Maximilian-Winter/llama-cpp-agent" target="_blank" rel="noreferrer" style="padding: .5rem;"> <svg width="24" height="24" fill="currentColor" viewBox="3 3 18 18"> <title>GitHub</title> <path d="M12 3C7.0275 3 3 7.12937 3 12.2276C3 16.3109 5.57625 19.7597 9.15374 20.9824C9.60374 21.0631 9.77249 20.7863 9.77249 20.5441C9.77249 20.3249 9.76125 19.5982 9.76125 18.8254C7.5 19.2522 6.915 18.2602 6.735 17.7412C6.63375 17.4759 6.19499 16.6569 5.8125 16.4378C5.4975 16.2647 5.0475 15.838 5.80124 15.8264C6.51 15.8149 7.01625 16.4954 7.18499 16.7723C7.99499 18.1679 9.28875 17.7758 9.80625 17.5335C9.885 16.9337 10.1212 16.53 10.38 16.2993C8.3775 16.0687 6.285 15.2728 6.285 11.7432C6.285 10.7397 6.63375 9.9092 7.20749 9.26326C7.1175 9.03257 6.8025 8.08674 7.2975 6.81794C7.2975 6.81794 8.05125 6.57571 9.77249 7.76377C10.4925 7.55615 11.2575 7.45234 12.0225 7.45234C12.7875 7.45234 13.5525 7.55615 14.2725 7.76377C15.9937 6.56418 16.7475 6.81794 16.7475 6.81794C17.2424 8.08674 16.9275 9.03257 16.8375 9.26326C17.4113 9.9092 17.76 10.7281 17.76 11.7432C17.76 15.2843 15.6563 16.0687 13.6537 16.2993C13.98 16.5877 14.2613 17.1414 14.2613 18.0065C14.2613 19.2407 14.25 20.2326 14.25 20.5441C14.25 20.7863 14.4188 21.0746 14.8688 20.9824C16.6554 20.364 18.2079 19.1866 19.3078 17.6162C20.4077 16.0457 20.9995 14.1611 21 12.2276C21 7.12937 16.9725 3 12 3Z"></path> </svg> </a> </div> </div> </div></div>"""
232
-
233
-
234
- # --- Gradio Komponenten (Dynamisch befüllt) ---
235
 
236
- # Das erste Element aus der dynamisch befüllten Liste als Standardwert nehmen
237
  default_model = MODEL_DROPDOWN_CHOICES[0] if MODEL_DROPDOWN_CHOICES else None
238
 
239
  model_dropdown = gr.Dropdown(
@@ -266,7 +139,6 @@ repeat_penalty_slider = gr.Slider(
266
  label="Repetition penalty",
267
  )
268
 
269
- # --- Gradio Chat Interface Definition (Unverändert) ---
270
  demo = gr.ChatInterface(
271
  respond,
272
  type="messages",
@@ -294,13 +166,11 @@ demo = gr.ChatInterface(
294
  code_background_fill_dark="#292733",
295
  ),
296
  css=css,
297
- description="Llama-cpp-agent: Chat multi llm selection",
298
  )
299
 
300
- # --- App starten ---
301
  if __name__ == "__main__":
302
- # Stelle sicher, dass der Default-Wert im Dropdown gesetzt ist, bevor gestartet wird
303
  if default_model:
304
  demo.launch()
305
  else:
306
- print("Konnte keine Modelle laden oder konfigurieren. App wird nicht gestartet.")
 
1
  import spaces
2
  import json
3
  import os
4
+ import glob
5
+ import subprocess
6
+
7
  from llama_cpp import Llama
8
  from llama_cpp_agent import LlamaCppAgent, MessagesFormatterType
9
  from llama_cpp_agent.providers import LlamaCppPythonProvider
 
11
  from llama_cpp_agent.chat_history.messages import Roles
12
  import gradio as gr
13
  from huggingface_hub import hf_hub_download, list_repo_files
14
+ from model_loader import MODEL_DROPDOWN_CHOICES, MODEL_FILE_MAPPING
15
 
16
  # --- Globale Konfiguration und Variablen ---
17
  llm = None
18
  llm_model = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  css = """.bubble-wrap { padding-top: calc(var(--spacing-xl) * 3) !important;}.message-row { justify-content: space-evenly !important; width: 100% !important; max-width: 100% !important; margin: calc(var(--spacing-xl)) 0 !important; padding: 0 calc(var(--spacing-xl) * 3) !important;}.flex-wrap.user { border-bottom-right-radius: var(--radius-lg) !important;}.flex-wrap.bot { border-bottom-left-radius: var(--radius-lg) !important;}.message.user{ padding: 10px;}.message.bot{ text-align: right; width: 100%; padding: 10px; border-radius: 10px;}.message-bubble-border { border-radius: 6px !important;}.message-buttons { justify-content: flex-end !important;}.message-buttons-left { align-self: end !important;}.message-buttons-bot, .message-buttons-user { right: 10px !important; left: auto !important; bottom: 2px !important;}.dark.message-bubble-border { border-color: #343140 !important;}.dark.user { background: #1e1c26 !important;}.dark.assistant.dark, .dark.pending.dark { background: #16141c !important;}"""
21
 
 
22
  def get_messages_formatter_type(model_name):
 
23
  if "Llama" in model_name:
24
  return MessagesFormatterType.LLAMA_3
25
  elif "Mistral" in model_name:
26
  return MessagesFormatterType.MISTRAL
 
27
  elif "GLM" in model_name or "Granite" in model_name:
28
  return MessagesFormatterType.CHATML
29
  else:
 
31
  return MessagesFormatterType.CHATML
32
 
33
  # ----------------------------------------------------------------------
34
+ ## Main Response Function for ChatInterface
35
  # ----------------------------------------------------------------------
36
 
37
  @spaces.GPU(duration=45)
 
49
  global llm
50
  global llm_model
51
 
 
52
  model_file_path = MODEL_FILE_MAPPING.get(selected_model_name)
53
 
54
  if not model_file_path:
55
+ return f"Error: Model file for '{selected_model_name}' not found. Has the download completed?"
56
 
57
  chat_template = get_messages_formatter_type(selected_model_name)
58
 
 
59
  if llm is None or llm_model != model_file_path:
60
+ print(f"Loading new model: {model_file_path}")
61
  try:
62
  llm = Llama(
63
  model_path=model_file_path,
 
68
  )
69
  llm_model = model_file_path
70
  except Exception as e:
71
+ return f"Error during loading of Llama model '{selected_model_name}' ({model_file_path}): {e}"
72
 
 
73
  provider = LlamaCppPythonProvider(llm)
74
  agent = LlamaCppAgent(
75
  provider,
 
86
  settings.repeat_penalty = repeat_penalty
87
  settings.stream = True
88
 
 
89
  messages = BasicChatHistory()
90
  for msn in history:
91
  role = Roles.user if msn.get('role') == 'user' else Roles.assistant
92
  messages.add_message({'role': role, 'content': msn.get('content', '')})
93
 
 
94
  stream = agent.get_chat_response(
95
  message,
96
  llm_sampling_settings=settings,
 
104
  outputs += output
105
  yield outputs
106
 
107
+ PLACEHOLDER = """<div class="message-bubble-border" style="display:flex; max-width: 600px; border-radius: 6px; border-width: 1px; border-color: #e5e7eb; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); backdrop-filter: blur(10px);"> <div style="padding: .5rem 1.5rem;display: flex;flex-direction: column;justify-content: space-evenly;"> <h2 style="text-align: left; font-size: 1.5rem; font-weight: 700; margin-bottom: 0.5rem;">llama.cpp based quantized gguf inference</h2> <p style="text-align: left; font-size: 16px; line-height: 1.5; margin-bottom: 15px;">This space hosts an Advanced model.</p> </div></div>"""
 
 
 
 
108
 
109
+ # --- Gradio Components (Dynamically populated) ---
110
  default_model = MODEL_DROPDOWN_CHOICES[0] if MODEL_DROPDOWN_CHOICES else None
111
 
112
  model_dropdown = gr.Dropdown(
 
139
  label="Repetition penalty",
140
  )
141
 
 
142
  demo = gr.ChatInterface(
143
  respond,
144
  type="messages",
 
166
  code_background_fill_dark="#292733",
167
  ),
168
  css=css,
169
+ description="Advanced model",
170
  )
171
 
 
172
  if __name__ == "__main__":
 
173
  if default_model:
174
  demo.launch()
175
  else:
176
+ print("Could not load any models or configure. App will not start.")