demetz commited on
Commit
ef0cac9
·
verified ·
1 Parent(s): 95549b3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -189
app.py CHANGED
@@ -1,147 +1,9 @@
1
- # import gradio as gr
2
- # from huggingface_hub import InferenceClient
3
- # from sentence_transformers import SentenceTransformer
4
- # import torch
5
-
6
- # # Load knowledge
7
- # with open("knowledge.txt", "r", encoding="utf-8") as file:
8
- # knowledge = file.read()
9
-
10
- # cleaned_chunks = [chunk.strip() for chunk in knowledge.strip().split("\n") if chunk.strip()]
11
- # model = SentenceTransformer('all-MiniLM-L6-v2')
12
- # chunk_embeddings = model.encode(cleaned_chunks, convert_to_tensor=True)
13
-
14
- # def get_top_chunks(query):
15
- # query_embedding = model.encode(query, convert_to_tensor=True)
16
- # query_embedding_normalized = query_embedding / query_embedding.norm()
17
- # similarities = torch.matmul(chunk_embeddings, query_embedding_normalized)
18
- # top_indices = torch.topk(similarities, k=5).indices.tolist()
19
- # return [cleaned_chunks[i] for i in top_indices]
20
-
21
- # client = InferenceClient("mistralai/Mistral-7B-Instruct-v0.2")
22
-
23
- # def respond(message, history, name, char_class, char_alignment):
24
- # response = ""
25
- # top_chunks = get_top_chunks(message)
26
- # context = "\n".join(top_chunks)
27
-
28
- # messages = [
29
- # {
30
- # "role": "system",
31
- # "content": (
32
- # f"You are a chatbot that helps users create characters for role-playing games."
33
- # f"The user might also provide the following information, please include their inputs in your response: \n Character name: {name}, Character Class: {char_class}, Character Alignment: {char_alignment}"
34
- # f"Use the following knowledge to inform your answers:\n\n{context}\n\n"
35
- # "Keep your answers under 300 words."
36
- # )
37
- # }
38
- # ]
39
-
40
- # if history:
41
- # messages.extend(history)
42
-
43
- # messages.append({"role": "user", "content": message})
44
-
45
- # stream = client.chat_completion(
46
- # messages,
47
- # max_tokens=300,
48
- # temperature=1.2,
49
- # stream=True,
50
- # )
51
-
52
- # for message in stream:
53
- # token = message.choices[0].delta.content
54
- # if token is not None:
55
- # response += token
56
- # yield response
57
-
58
- # # === GUI ===
59
-
60
- # chat_css="""
61
- # #alignment_radio .gr-radio {
62
- # display: grid !important;
63
- # grid-template-columns: repeat(3, 1fr);
64
- # gap: 0 !important;
65
- # width: 300px;
66
- # }
67
-
68
- # #alignment_radio input[type="radio"] {
69
- # display: none;
70
- # }
71
-
72
- # #alignment_radio label {
73
- # display: flex !important;
74
- # align-items: center;
75
- # justify-content: center;
76
- # aspect-ratio: 1 / 1;
77
- # background-color: #eee;
78
- # border: 1px solid #ccc;
79
- # font-size: 0.75rem;
80
- # margin: 0 !important;
81
- # padding: 0 !important;
82
- # cursor: pointer;
83
- # user-select: none;
84
- # transition: background-color 0.2s, color 0.2s;
85
- # }
86
-
87
- # /* This is the magic: target the label of the checked input */
88
- # #alignment_radio input[type="radio"]:checked + label {
89
- # background-color: red !important;
90
- # color: white !important;
91
- # border-color: darkred !important;
92
- # }
93
- # """
94
-
95
- # js = """
96
- # <script>
97
- # window.addEventListener('load', () => {
98
- # const container = document.querySelector('#alignment_radio .gr-radio');
99
- # if (container) {
100
- # container.classList.add('radio-grid');
101
- # Array.from(container.querySelectorAll('input[type="radio"]')).forEach(input => {
102
- # const wrapper = document.createElement('div');
103
- # wrapper.classList.add('radio-wrapper');
104
- # const label = container.querySelector(`label[for="${input.id}"]`);
105
- # input.replaceWith(wrapper);
106
- # wrapper.appendChild(input);
107
- # if (label) wrapper.appendChild(label);
108
- # });
109
- # }
110
- # });
111
- # </script>
112
- # """
113
-
114
- # with gr.Blocks(css=chat_css, js=js) as chatbot:
115
- # with gr.Row(scale=1):
116
- # with gr.Column(scale=1):
117
- # gr.Image(
118
- # value="frog.png",
119
- # show_label=False,
120
- # show_share_button=False,
121
- # show_download_button=False
122
- # )
123
- # with gr.Column(scale=1):
124
- # character_name = gr.Textbox(label = "Character Name", placeholder="Type your name here…", info ="optional")
125
- # character_class = gr.CheckboxGroup(['Barbarian', 'Bard', 'Cleric', 'Druid', 'Fighter', 'Monk', 'Paladin', 'Ranger', 'Rogue', 'Sorcerer', 'Warlock', 'Wizard'], label="Character Class", info="Choose one or more")
126
- # character_alignment = gr.Radio(["Lawful Good", "Neutral Good", "Chaotic Good", "Lawful Neutral", "True Neutral", "Chaotic Neutral", "Lawful Evil", "Neutral Evil", "Chaotic Evil"], elem_id="alignment_radio")
127
-
128
- # gr.ChatInterface(
129
- # fn=respond,
130
- # additional_inputs=[character_name, character_class, character_alignment], # Pass name into function!
131
- # type="messages",
132
- # examples=None,
133
- # title="Character Creator",
134
- # description="Welcome! Tell me what you want to create and we can make your character come to life!"
135
- # )
136
-
137
- # chatbot.launch()
138
-
139
  import gradio as gr
140
  from huggingface_hub import InferenceClient
141
  from sentence_transformers import SentenceTransformer
142
  import torch
143
 
144
- # === Load knowledge ===
145
  with open("knowledge.txt", "r", encoding="utf-8") as file:
146
  knowledge = file.read()
147
 
@@ -167,9 +29,9 @@ def respond(message, history, name, char_class, char_alignment):
167
  {
168
  "role": "system",
169
  "content": (
170
- f"You are a chatbot that helps users create characters for role-playing games.\n"
171
- f"The user might provide: Character name: {name}, Class: {char_class}, Alignment: {char_alignment}.\n"
172
- f"Use the following knowledge:\n\n{context}\n\n"
173
  "Keep your answers under 300 words."
174
  )
175
  }
@@ -193,71 +55,56 @@ def respond(message, history, name, char_class, char_alignment):
193
  response += token
194
  yield response
195
 
196
- # === Alignment UI Setup ===
197
- alignment_choices = [
198
- "Lawful Good", "Neutral Good", "Chaotic Good",
199
- "Lawful Neutral", "True Neutral", "Chaotic Neutral",
200
- "Lawful Evil", "Neutral Evil", "Chaotic Evil"
201
- ]
202
 
203
- chat_css = """
204
- #alignment_container {
205
- display: grid;
206
- grid-template-columns: repeat(3, 1fr);
207
- width: 300px;
208
- gap: 0;
209
  }
210
- .alignment-btn {
 
 
 
 
211
  aspect-ratio: 1 / 1;
212
  background-color: #eee;
213
- border: 1px solid #aaa;
214
  font-size: 0.75rem;
215
- margin: 0;
216
- padding: 0;
217
  cursor: pointer;
 
 
218
  }
219
- .alignment-btn.selected {
 
 
220
  background-color: red !important;
221
- color: white;
222
- border-color: darkred;
223
  }
224
  """
225
 
226
- # === Button state update function ===
227
- def update_alignment(choice):
228
- return [
229
- gr.Button.update(elem_classes=["alignment-btn", "selected"] if choice == c else ["alignment-btn"])
230
- for c in alignment_choices
231
- ] + [choice] # Last item is selected_alignment output
232
-
233
- # === GUI ===
234
  with gr.Blocks(css=chat_css) as chatbot:
235
- with gr.Row():
236
  with gr.Column(scale=1):
237
- gr.Image("frog.png", show_label=False)
 
 
 
 
 
238
  with gr.Column(scale=1):
239
- character_name = gr.Textbox(label="Character Name", placeholder="Type your name here…", info="optional")
240
- character_class = gr.CheckboxGroup(
241
- ['Barbarian', 'Bard', 'Cleric', 'Druid', 'Fighter', 'Monk', 'Paladin',
242
- 'Ranger', 'Rogue', 'Sorcerer', 'Warlock', 'Wizard'],
243
- label="Character Class", info="Choose one or more")
244
-
245
- selected_alignment = gr.State("")
246
-
247
- with gr.Row(elem_id="alignment_container"):
248
- buttons = [gr.Button(value=c, elem_classes=["alignment-btn"]) for c in alignment_choices]
249
-
250
- for btn, choice in zip(buttons, alignment_choices):
251
- btn.click(
252
- fn=update_alignment,
253
- inputs=[gr.State(choice)],
254
- outputs=buttons + [selected_alignment] # ✅ Fixed here
255
- )
256
 
257
  gr.ChatInterface(
258
  fn=respond,
259
- additional_inputs=[character_name, character_class, selected_alignment],
260
  type="messages",
 
261
  title="Character Creator",
262
  description="Welcome! Tell me what you want to create and we can make your character come to life!"
263
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  from sentence_transformers import SentenceTransformer
4
  import torch
5
 
6
+ # Load knowledge
7
  with open("knowledge.txt", "r", encoding="utf-8") as file:
8
  knowledge = file.read()
9
 
 
29
  {
30
  "role": "system",
31
  "content": (
32
+ f"You are a chatbot that helps users create characters for role-playing games."
33
+ f"The user might also provide the following information, please include their inputs in your response: \n Character name: {name}, Character Class: {char_class}, Character Alignment: {char_alignment}"
34
+ f"Use the following knowledge to inform your answers:\n\n{context}\n\n"
35
  "Keep your answers under 300 words."
36
  )
37
  }
 
55
  response += token
56
  yield response
57
 
58
+ # === GUI ===
59
+
60
+ chat_css="""
 
 
 
61
 
62
+ #alignment_radio input[type="radio"] {
63
+ display: none;
 
 
 
 
64
  }
65
+
66
+ #alignment_radio label {
67
+ display: flex !important;
68
+ align-items: center;
69
+ justify-content: center;
70
  aspect-ratio: 1 / 1;
71
  background-color: #eee;
72
+ border: 1px solid #ccc;
73
  font-size: 0.75rem;
74
+ margin: 0 !important;
75
+ padding: 0 !important;
76
  cursor: pointer;
77
+ user-select: none;
78
+ transition: background-color 0.2s, color 0.2s;
79
  }
80
+
81
+ /* This is the magic: target the label of the checked input */
82
+ #alignment_radio input[type="radio"]:checked + label {
83
  background-color: red !important;
84
+ color: white !important;
85
+ border-color: darkred !important;
86
  }
87
  """
88
 
 
 
 
 
 
 
 
 
89
  with gr.Blocks(css=chat_css) as chatbot:
90
+ with gr.Row(scale=1):
91
  with gr.Column(scale=1):
92
+ gr.Image(
93
+ value="frog.png",
94
+ show_label=False,
95
+ show_share_button=False,
96
+ show_download_button=False
97
+ )
98
  with gr.Column(scale=1):
99
+ character_name = gr.Textbox(label = "Character Name", placeholder="Type your name here…", info ="optional")
100
+ character_class = gr.CheckboxGroup(['Barbarian', 'Bard', 'Cleric', 'Druid', 'Fighter', 'Monk', 'Paladin', 'Ranger', 'Rogue', 'Sorcerer', 'Warlock', 'Wizard'], label="Character Class", info="Choose one or more")
101
+ character_alignment = gr.Radio(["Lawful Good", "Neutral Good", "Chaotic Good", "Lawful Neutral", "True Neutral", "Chaotic Neutral", "Lawful Evil", "Neutral Evil", "Chaotic Evil"], elem_id="alignment_radio")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
  gr.ChatInterface(
104
  fn=respond,
105
+ additional_inputs=[character_name, character_class, character_alignment], # Pass name into function!
106
  type="messages",
107
+ examples=None,
108
  title="Character Creator",
109
  description="Welcome! Tell me what you want to create and we can make your character come to life!"
110
  )