trinity-tandon commited on
Commit
5dcb704
·
verified ·
1 Parent(s): 6bf6136

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -46
app.py CHANGED
@@ -1,64 +1,122 @@
1
  import gradio as gr
 
 
2
  from huggingface_hub import InferenceClient
 
 
3
 
4
- """
5
- 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
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  messages.append({"role": "user", "content": message})
27
 
28
  response = ""
29
-
30
  for message in client.chat_completion(
 
31
  messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
 
36
  ):
37
  token = message.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
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
-
62
-
63
- if __name__ == "__main__":
64
- demo.launch()
 
1
  import gradio as gr
2
+ import random
3
+ import os
4
  from huggingface_hub import InferenceClient
5
+ from sentence_transformers import SentenceTransformer
6
+ import torch
7
 
8
+ with open("knowledge.txt", "r", encoding="utf-8") as file:
9
+ recent = file.read()
10
+ # opens the text, saves as "file"
11
+ # reads the text and saves as water_cycle_text variable
12
 
13
 
 
 
 
 
 
 
 
 
 
14
 
15
+ cleaned_text = recent.strip()
16
+ # cleaning up the text
17
+ chunks = cleaned_text.split("\n")
18
+ # seperating the text into one sentence pieces
19
+ cleaned_chunks = []
20
+ # creating an empty list to put the cleaned chunks in
21
 
22
+ for chunk in chunks:
23
+ stripped_chunk = chunk.strip()
24
+ if stripped_chunk:
25
+ cleaned_chunks.append(stripped_chunk)
26
+ # loop through chunks and add not empty chunks to cleaned_chunks list
27
+
28
+
29
+ model = SentenceTransformer('all-MiniLM-L6-v2')
30
+
31
+ chunk_embeddings = model.encode(cleaned_chunks, convert_to_tensor=True)
32
+ # encode the model, pass through my cleaned chunks and convert to vector embeddings (not arrays)
33
+
34
+
35
+ def get_top_chunks(query):
36
+ # create my function taking query as parameter
37
+ query_embedding = model.encode(query, convert_to_tensor=True)
38
+ # encode query to vector embedding for comparison
39
+ query_embedding_normalized = query_embedding / query_embedding.norm()
40
+ # normalize my query to 1; allows for comparison of meaning
41
+ chunk_embeddings_normalized = chunk_embeddings / chunk_embeddings.norm(dim=1, keepdim=True)
42
+ # normailizing chunks for comparison of meaning
43
+
44
+ similarities = torch.matmul(chunk_embeddings_normalized, query_embedding_normalized)
45
+
46
+ # using matmul (matrix multiplication method) to compare query to chunks
47
+ top_indices = torch.topk(similarities, k=3).indices
48
+
49
+ # get the indices of the chunks that are most similar to query
50
+
51
+ top_chunks = []
52
+
53
+ for i in top_indices:
54
+ chunk = chunks[i]
55
+ # for each index number in top_indices, get back the text
56
+ top_chunks.append(chunk)
57
+ # values of each index number is added to top_chunks
58
+ return top_chunks
59
+
60
+ client = InferenceClient(
61
+ model='Qwen/Qwen2.5-72B-Instruct',
62
+ #token = 'HF_TOKEN'
63
+ )
64
+
65
+ #client is where you can change the LLM model!
66
+ def respond(message,history):
67
+ if not message.strip():
68
+ return "Hello!"
69
+ gift_ideas = get_top_chunks(message)
70
+ messages = [{'role': 'system', 'content': f'You give really good gift ideas and are super helpful! You also tell me the price of each item. Give me 5 gift ideas if I ask. Use the following database for gift ideas: {gift_ideas}'}]
71
+
72
+ if history:
73
+ messages.extend(history)
74
+
75
  messages.append({"role": "user", "content": message})
76
 
77
  response = ""
 
78
  for message in client.chat_completion(
79
+ #max_tokens controls how many words your responses is
80
  messages,
81
+ max_tokens = 500,
82
+ stream = True,
83
+
84
+ #temperature = 0.8, #code a decimal between 0-2
85
+ #top_p = .65 #code a decimal between 0-1
86
  ):
87
  token = message.choices[0].delta.content
 
88
  response += token
89
  yield response
90
+ #print(response["choices"][0]["message"]["content"].strip())
91
+
92
+ #yield response["choices"][0]["message"]["content"].strip()
93
+
94
+ #with gr.Blocks(theme='hmb/amethyst') as demo:
95
+ # with gr.Row(equal_height=True):
96
+ # with gr.Column(scale=10):
97
+ # """
98
+ # # 🎁 Introducing WrapIT!
99
+ # **WrapIT** helps users find personalized gift ideas and craft thoughtful card messages
100
+ # by inputting details like the recipient's interests, celebration type, and budget.
101
+ #
102
+ # ✨ *All you have to do is wrap it.*
103
+ # """
104
+ # )
105
+ # gr.ChatInterface(respond, type='messages')
106
 
107
+
108
+
109
+ #chatbot = gr.Chatbot()
110
+ #msg = gr.Textbox(placeholder="Say hi to WrapIT here!", label="Message")
111
+ #send = gr.Button("Send")
112
 
113
+ #msg.submit(respond, [msg, chatbot], [msg, chatbot])
114
+ #send.click(respond, [msg, chatbot], [msg, chatbot])
115
+ suggestions = ["Hello", "How are you?"]
116
+ chat_interface = gr.ChatInterface(
117
+ fn=respond,
118
+ title="🎁 Introducing WrapIT!",
119
+ theme='hmb/amethyst',
120
+ description=" **WrapIT** helps users find personalized gift ideas and craft thoughtful card messages by inputting details like the recipient's interests, celebration type, and budget ✨ *All you have to do is wrap it.*")
121
+ examples=suggestions
122
+ chat_interface.launch()