jpmendes commited on
Commit
035861b
verified
1 Parent(s): e89dcba

Upload 4 files

Browse files
Files changed (4) hide show
  1. app.py +54 -54
  2. download_models.py +24 -0
  3. install.sh +5 -0
  4. requirements.txt +1 -0
app.py CHANGED
@@ -1,70 +1,70 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
3
 
 
 
 
 
 
 
4
 
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
14
  """
15
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
16
  """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
-
19
- messages = [{"role": "system", "content": system_message}]
20
-
21
- messages.extend(history)
 
 
 
 
22
 
23
- messages.append({"role": "user", "content": message})
 
24
 
25
- response = ""
26
-
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
 
41
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- chatbot = gr.ChatInterface(
47
- respond,
48
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
- )
62
 
 
63
  with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
 
 
 
 
67
 
 
 
 
 
 
 
68
 
69
  if __name__ == "__main__":
70
  demo.launch()
 
1
  import gradio as gr
2
+ import subprocess
3
+ from pathlib import Path
4
 
5
+ # Caminhos dos modelos
6
+ MODEL_DIR = Path("./models")
7
+ MODELS = {
8
+ "Q3_K_XL (Inferior)": MODEL_DIR / "Llama-3.2-1B-Instruct-Q3_K_XL.gguf",
9
+ "Q4_K_M (Alta)": MODEL_DIR / "Llama-3.2-1B-Instruct-Q4_K_M.gguf",
10
+ }
11
 
12
+ # Hist贸rico global de chat
13
+ history_dict = {}
14
+
15
+ def run_llama(prompt, model_path, max_tokens, temperature):
 
 
 
 
 
16
  """
17
+ Executa o llama.cpp localmente e retorna a sa铆da
18
  """
19
+ cmd = [
20
+ "./llama.cpp/main",
21
+ "-m", str(model_path),
22
+ "-p", prompt,
23
+ "-n", str(max_tokens),
24
+ "-t", "4",
25
+ "-temp", str(temperature),
26
+ "--color", "false",
27
+ ]
28
 
29
+ result = subprocess.run(cmd, capture_output=True, text=True)
30
+ return result.stdout.strip()
31
 
32
+ def respond(user_message, model_choice, max_tokens, temperature, session_id="default"):
33
+ """
34
+ Fun莽茫o chamada pelo Gradio, mant茅m hist贸rico
35
+ """
36
+ global history_dict
37
+ if session_id not in history_dict:
38
+ history_dict[session_id] = []
 
 
 
 
 
 
39
 
40
+ history = history_dict[session_id]
41
+ # Concatena hist贸rico em um 煤nico prompt
42
+ prompt = "\n".join([f"User: {m['user']}\nAI: {m['ai']}" for m in history])
43
+ prompt += f"\nUser: {user_message}\nAI:"
44
 
45
+ # Roda o llama.cpp
46
+ response = run_llama(prompt, MODELS[model_choice], max_tokens, temperature)
47
 
48
+ # Atualiza hist贸rico
49
+ history.append({"user": user_message, "ai": response})
50
+ return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
+ # Interface Gradio
53
  with gr.Blocks() as demo:
54
+ with gr.Row():
55
+ model_dropdown = gr.Dropdown(list(MODELS.keys()), label="Escolha o modelo")
56
+ user_input = gr.Textbox(label="Mensagem do usu谩rio")
57
+ with gr.Row():
58
+ max_tokens_slider = gr.Slider(1, 2048, value=512, step=1, label="Max tokens")
59
+ temperature_slider = gr.Slider(0.1, 4.0, value=0.7, step=0.1, label="Temperature")
60
+ output_box = gr.Textbox(label="Resposta")
61
 
62
+ btn = gr.Button("Enviar")
63
+ btn.click(
64
+ respond,
65
+ inputs=[user_input, model_dropdown, max_tokens_slider, temperature_slider],
66
+ outputs=[output_box],
67
+ )
68
 
69
  if __name__ == "__main__":
70
  demo.launch()
download_models.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import hf_hub_download
2
+ from pathlib import Path
3
+
4
+ # Cria pasta models se n茫o existir
5
+ MODEL_DIR = Path("./models")
6
+ MODEL_DIR.mkdir(exist_ok=True)
7
+
8
+ # Dicion谩rio com os modelos e os arquivos GGUF correspondentes
9
+ MODELS = {
10
+ "Q3_K_XL": "Llama-3.2-1B-Instruct-Q3_K_XL.gguf",
11
+ "Q4_K_M": "Llama-3.2-1B-Instruct-Q4_K_M.gguf",
12
+ }
13
+
14
+ REPO_ID = "bartowski/Llama-3.2-1B-Instruct-GGUF"
15
+
16
+ for key, file_name in MODELS.items():
17
+ print(f"Baixando {file_name}...")
18
+ path = hf_hub_download(
19
+ repo_id=REPO_ID,
20
+ filename=file_name,
21
+ local_dir=MODEL_DIR,
22
+ force_filename=file_name
23
+ )
24
+ print(f"{file_name} salvo em {path}")
install.sh ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Compila o llama.cpp no Space
3
+ cd llama.cpp
4
+ make
5
+ cd ..
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ gradio