abrah926 commited on
Commit
cd618c5
Β·
verified Β·
1 Parent(s): 57bc577

updating app.py to auto run scripts

Browse files
Files changed (1) hide show
  1. app.py +38 -76
app.py CHANGED
@@ -1,42 +1,58 @@
1
- import os
2
  import gradio as gr
3
  from huggingface_hub import InferenceClient
4
  from datasets import load_dataset
5
- import time
6
  import faiss
7
  import numpy as np
 
 
8
 
9
- # βœ… Install FAISS if missing
10
  os.system("pip install faiss-cpu")
11
 
12
  def log(message):
13
  print(f"βœ… {message}")
14
 
15
-
16
  # βœ… Load the datasets
 
17
  datasets = {
18
  "sales": load_dataset("goendalf666/sales-conversations", trust_remote_code=True),
19
  "blended": load_dataset("blended_skill_talk", trust_remote_code=True),
20
  "dialog": load_dataset("daily_dialog", trust_remote_code=True),
21
  "multiwoz": load_dataset("multi_woz_v22", trust_remote_code=True),
22
  }
 
 
 
 
 
23
 
24
- # Optional: Print dataset names and sizes
25
- for name, dataset in datasets.items():
26
- print(f"{name}: {len(dataset['train'])} examples")
27
 
28
- # Initialize the model client (use correct model for chatbot)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  client = InferenceClient("mistralai/Mistral-7B-Instruct-v0.3")
30
 
31
- # Chatbot response function
32
- def respond(
33
- message,
34
- history: list[tuple[str, str]],
35
- system_message,
36
- max_tokens,
37
- temperature,
38
- top_p,
39
- ):
40
  messages = [{"role": "system", "content": system_message}]
41
 
42
  for val in history:
@@ -46,81 +62,27 @@ def respond(
46
  messages.append({"role": "assistant", "content": val[1]})
47
 
48
  messages.append({"role": "user", "content": message})
49
-
50
  response = ""
51
 
52
  for message in client.chat_completions(
53
- messages,
54
- max_tokens=max_tokens,
55
- stream=True,
56
- temperature=temperature,
57
- top_p=top_p,
58
  ):
59
  token = message["choices"][0]["delta"]["content"]
60
  response += token
61
  yield response
62
 
63
-
64
- # Gradio interface for chatbot
65
  demo = gr.ChatInterface(
66
  respond,
67
  additional_inputs=[
68
  gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
69
  gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
70
  gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
71
- gr.Slider(
72
- minimum=0.1,
73
- maximum=1.0,
74
- value=0.95,
75
- step=0.05,
76
- label="Top-p (nucleus sampling)",
77
- ),
78
  ],
79
  )
80
 
81
- def start_embedding():
82
- # Include your embedding logic here (from embeddings.py)
83
- log("Embedding started...")
84
- time.sleep(2) # Simulating embedding process
85
- log("Embedding process finished.")
86
-
87
- # Create Gradio interface with a button to start the embedding
88
- demo = gr.Interface(
89
- fn=start_embedding,
90
- inputs=None,
91
- outputs="text",
92
- live=True,
93
- title="Embedding Trigger"
94
- )
95
-
96
-
97
- # βœ… Function to check FAISS index
98
- def check_faiss():
99
- index_path = "my_embeddings" # Adjust if needed
100
-
101
- try:
102
- index = faiss.read_index(index_path)
103
- num_vectors = index.ntotal
104
- dim = index.d
105
-
106
- if num_vectors > 0:
107
- sample_vectors = index.reconstruct_n(0, min(5, num_vectors)) # Get first 5 embeddings
108
- return f"πŸ“Š FAISS index contains {num_vectors} vectors.\nβœ… Embedding dimension: {dim}\n🧐 Sample: {sample_vectors[:2]} ..."
109
- else:
110
- return "⚠️ No embeddings found in FAISS index!"
111
-
112
- except Exception as e:
113
- return f"❌ ERROR: Failed to load FAISS index - {e}"
114
-
115
- # βœ… Add a Gradio button to trigger FAISS check
116
- with gr.Blocks() as demo:
117
- gr.Markdown("### πŸ” FAISS Embedding Check")
118
-
119
- check_button = gr.Button("πŸ”Ž Check FAISS Embeddings")
120
- output_text = gr.Textbox(label="FAISS Status", interactive=False)
121
-
122
- check_button.click(fn=check_faiss, outputs=output_text)
123
-
124
- # Launch Gradio app
125
  if __name__ == "__main__":
126
  demo.launch()
 
 
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  from datasets import load_dataset
 
4
  import faiss
5
  import numpy as np
6
+ import os
7
+ import time
8
 
9
+ # βœ… Ensure FAISS is installed
10
  os.system("pip install faiss-cpu")
11
 
12
  def log(message):
13
  print(f"βœ… {message}")
14
 
 
15
  # βœ… Load the datasets
16
+ log("πŸ“₯ Loading datasets...")
17
  datasets = {
18
  "sales": load_dataset("goendalf666/sales-conversations", trust_remote_code=True),
19
  "blended": load_dataset("blended_skill_talk", trust_remote_code=True),
20
  "dialog": load_dataset("daily_dialog", trust_remote_code=True),
21
  "multiwoz": load_dataset("multi_woz_v22", trust_remote_code=True),
22
  }
23
+ log("βœ… Datasets loaded.")
24
+
25
+ # βœ… Step 1: Run Embedding Script (Import and Run)
26
+ log("πŸš€ Running embeddings script...")
27
+ import embeddings # This will automatically run embeddings.py
28
 
29
+ time.sleep(5) # Wait for embeddings to be created
 
 
30
 
31
+ # βœ… Step 2: Check FAISS index
32
+ def check_faiss():
33
+ index_path = "my_embeddings" # Adjust if needed
34
+
35
+ try:
36
+ index = faiss.read_index(index_path)
37
+ num_vectors = index.ntotal
38
+ dim = index.d
39
+
40
+ if num_vectors > 0:
41
+ return f"πŸ“Š FAISS index contains {num_vectors} vectors.\nβœ… Embedding dimension: {dim}"
42
+ else:
43
+ return "⚠️ No embeddings found in FAISS index!"
44
+
45
+ except Exception as e:
46
+ return f"❌ ERROR: Failed to load FAISS index - {e}"
47
+
48
+ log("πŸ” Checking FAISS embeddings...")
49
+ faiss_status = check_faiss()
50
+ log(faiss_status)
51
+
52
+ # βœ… Step 3: Initialize chatbot
53
  client = InferenceClient("mistralai/Mistral-7B-Instruct-v0.3")
54
 
55
+ def respond(message, history, system_message, max_tokens, temperature, top_p):
 
 
 
 
 
 
 
 
56
  messages = [{"role": "system", "content": system_message}]
57
 
58
  for val in history:
 
62
  messages.append({"role": "assistant", "content": val[1]})
63
 
64
  messages.append({"role": "user", "content": message})
 
65
  response = ""
66
 
67
  for message in client.chat_completions(
68
+ messages, max_tokens=max_tokens, stream=True, temperature=temperature, top_p=top_p
 
 
 
 
69
  ):
70
  token = message["choices"][0]["delta"]["content"]
71
  response += token
72
  yield response
73
 
74
+ # βœ… Step 4: Start Chatbot Interface
 
75
  demo = gr.ChatInterface(
76
  respond,
77
  additional_inputs=[
78
  gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
79
  gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
80
  gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
81
+ gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
 
 
 
 
 
 
82
  ],
83
  )
84
 
85
+ log("βœ… All systems go! Launching chatbot...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  if __name__ == "__main__":
87
  demo.launch()
88
+