DHEIVER commited on
Commit
9bf186c
·
verified ·
1 Parent(s): bb97b78

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -90
app.py CHANGED
@@ -1,5 +1,5 @@
1
  import gradio as gr
2
- from typing import List, Tuple
3
  from gradio_client import Client
4
 
5
  def create_chat_app():
@@ -18,6 +18,7 @@ def create_chat_app():
18
  "max_tokens_label": "Maximum Tokens",
19
  "temperature_label": "Temperature",
20
  "top_p_label": "Top-p (Nucleus Sampling)",
 
21
  "info_section": """
22
  ### ℹ️ Information
23
  - Model: Llama 3.3 70B Instruct
@@ -25,14 +26,13 @@ def create_chat_app():
25
  - Hosting: Hugging Face Spaces
26
 
27
  For best performance, adjust the parameters according to your needs.
28
- This model has advanced natural language processing capabilities.
29
  """,
30
  "error_message": "Sorry, an error occurred: {}\nPlease check your connection and settings.",
31
  "examples": [
32
- ["Hello! How are you?"],
33
- ["Can you explain what artificial intelligence is?"],
34
- ["What is the capital of Brazil?"],
35
- ["Help me write a Python code to calculate Fibonacci."]
36
  ]
37
  },
38
  "pt": {
@@ -48,6 +48,7 @@ def create_chat_app():
48
  "max_tokens_label": "Máximo de Tokens",
49
  "temperature_label": "Temperatura",
50
  "top_p_label": "Top-p (Amostragem Nucleus)",
 
51
  "info_section": """
52
  ### ℹ️ Informações
53
  - Modelo: Llama 3.3 70B Instruct
@@ -55,34 +56,33 @@ def create_chat_app():
55
  - Hospedagem: Hugging Face Spaces
56
 
57
  Para melhor desempenho, ajuste os parâmetros de acordo com suas necessidades.
58
- Este modelo possui capacidades avançadas de processamento de linguagem natural.
59
  """,
60
  "error_message": "Desculpe, ocorreu um erro: {}\nPor favor, verifique sua conexão e configurações.",
61
  "examples": [
62
- ["Olá! Como você está?"],
63
- ["Pode me explicar o que é inteligência artificial?"],
64
- ["Qual é a capital do Brasil?"],
65
- ["Me ajude a escrever um código em Python para calcular fibonacci."]
66
  ]
67
  }
68
  }
69
 
70
  def respond(
71
  message: str,
72
- chat_history: List[Tuple[str, str]],
73
  system_message: str,
74
  max_tokens: int,
75
  temperature: float,
76
  top_p: float,
77
  language: str,
78
- ) -> Tuple[List[Tuple[str, str]], str]:
79
  try:
80
  client = Client("aifeifei798/feifei-chat")
81
 
 
82
  formatted_message = f"{system_message}\n\nConversation history:\n"
83
- for user, assistant in chat_history:
84
- formatted_message += f"User: {user}\n"
85
- formatted_message += f"Assistant: {assistant}\n"
86
 
87
  formatted_message += f"User: {message}"
88
 
@@ -99,107 +99,114 @@ def create_chat_app():
99
  api_name="/chat"
100
  )
101
 
102
- chat_history.append((message, response))
103
- return chat_history, "" # Return updated history and empty message
 
 
 
 
 
104
 
105
  except Exception as e:
106
  error_msg = TRANSLATIONS[language]["error_message"].format(str(e))
107
- chat_history.append((message, error_msg))
108
  return chat_history, ""
109
 
110
- def update_interface(language: str):
111
- trans = TRANSLATIONS[language]
112
- return (
113
- trans["title"],
114
- trans["description"],
115
- trans["system_message"],
116
- trans["system_message_label"],
117
- trans["max_tokens_label"],
118
- trans["temperature_label"],
119
- trans["top_p_label"],
120
- trans["info_section"]
121
- )
122
-
123
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
124
- # Language selector
125
- language = gr.Radio(
126
- choices=["en", "pt"],
127
- value="en",
128
- label="Language/Idioma",
129
- interactive=True
130
- )
131
 
132
- # Dynamic content containers
133
- title_md = gr.Markdown(TRANSLATIONS["en"]["title"])
134
- description_md = gr.Markdown(TRANSLATIONS["en"]["description"])
135
 
136
  with gr.Group():
137
  chatbot = gr.Chatbot(
138
  value=[],
139
  height=400,
140
- label=TRANSLATIONS["en"]["title"]
141
  )
142
- msg = gr.Textbox(
143
- label="Message",
144
- placeholder="Type your message here...",
145
  lines=3
146
  )
147
 
148
- with gr.Row():
149
- system_msg = gr.Textbox(
150
  value=TRANSLATIONS["en"]["system_message"],
151
  label=TRANSLATIONS["en"]["system_message_label"]
152
  )
153
- max_tokens = gr.Slider(
154
- minimum=1,
155
- maximum=4096,
156
- value=2048,
157
- step=1,
158
- label=TRANSLATIONS["en"]["max_tokens_label"]
159
- )
160
- temperature = gr.Slider(
161
- minimum=0.1,
162
- maximum=2.0,
163
- value=0.7,
164
- step=0.1,
165
- label=TRANSLATIONS["en"]["temperature_label"]
166
- )
167
- top_p = gr.Slider(
168
- minimum=0.1,
169
- maximum=1.0,
170
- value=0.95,
171
- step=0.05,
172
- label=TRANSLATIONS["en"]["top_p_label"]
 
 
 
 
 
 
 
 
 
 
173
  )
174
-
175
- info_md = gr.Markdown(TRANSLATIONS["en"]["info_section"])
176
 
177
- # Set up chat functionality
178
- msg.submit(
179
- respond,
180
- inputs=[msg, chatbot, system_msg, max_tokens, temperature, top_p, language],
181
- outputs=[chatbot, msg] # Update chat history and clear message input
182
- )
183
 
184
- # Examples
185
  gr.Examples(
186
  examples=TRANSLATIONS["en"]["examples"],
187
- inputs=msg
 
 
 
 
 
 
 
188
  )
189
 
190
- # Update interface when language changes
191
- language.change(
192
- fn=update_interface,
193
- inputs=[language],
 
 
 
 
 
 
 
 
 
 
 
 
 
194
  outputs=[
195
- title_md,
196
- description_md,
197
- system_msg,
198
- system_msg.label,
199
- max_tokens.label,
200
- temperature.label,
201
- top_p.label,
202
- info_md
203
  ]
204
  )
205
 
 
1
  import gradio as gr
2
+ from typing import List, Dict
3
  from gradio_client import Client
4
 
5
  def create_chat_app():
 
18
  "max_tokens_label": "Maximum Tokens",
19
  "temperature_label": "Temperature",
20
  "top_p_label": "Top-p (Nucleus Sampling)",
21
+ "message_placeholder": "Type your message here...",
22
  "info_section": """
23
  ### ℹ️ Information
24
  - Model: Llama 3.3 70B Instruct
 
26
  - Hosting: Hugging Face Spaces
27
 
28
  For best performance, adjust the parameters according to your needs.
 
29
  """,
30
  "error_message": "Sorry, an error occurred: {}\nPlease check your connection and settings.",
31
  "examples": [
32
+ "Hello! How are you?",
33
+ "Can you explain what artificial intelligence is?",
34
+ "What is the capital of Brazil?",
35
+ "Help me write a Python code to calculate Fibonacci."
36
  ]
37
  },
38
  "pt": {
 
48
  "max_tokens_label": "Máximo de Tokens",
49
  "temperature_label": "Temperatura",
50
  "top_p_label": "Top-p (Amostragem Nucleus)",
51
+ "message_placeholder": "Digite sua mensagem aqui...",
52
  "info_section": """
53
  ### ℹ️ Informações
54
  - Modelo: Llama 3.3 70B Instruct
 
56
  - Hospedagem: Hugging Face Spaces
57
 
58
  Para melhor desempenho, ajuste os parâmetros de acordo com suas necessidades.
 
59
  """,
60
  "error_message": "Desculpe, ocorreu um erro: {}\nPor favor, verifique sua conexão e configurações.",
61
  "examples": [
62
+ "Olá! Como você está?",
63
+ "Pode me explicar o que é inteligência artificial?",
64
+ "Qual é a capital do Brasil?",
65
+ "Me ajude a escrever um código em Python para calcular fibonacci."
66
  ]
67
  }
68
  }
69
 
70
  def respond(
71
  message: str,
72
+ chat_history: List[Dict],
73
  system_message: str,
74
  max_tokens: int,
75
  temperature: float,
76
  top_p: float,
77
  language: str,
78
+ ):
79
  try:
80
  client = Client("aifeifei798/feifei-chat")
81
 
82
+ # Format conversation history
83
  formatted_message = f"{system_message}\n\nConversation history:\n"
84
+ for msg in chat_history:
85
+ formatted_message += f"{msg['role']}: {msg['content']}\n"
 
86
 
87
  formatted_message += f"User: {message}"
88
 
 
99
  api_name="/chat"
100
  )
101
 
102
+ # Update chat history in the new format
103
+ chat_history.extend([
104
+ {"role": "user", "content": message},
105
+ {"role": "assistant", "content": response}
106
+ ])
107
+
108
+ return chat_history, ""
109
 
110
  except Exception as e:
111
  error_msg = TRANSLATIONS[language]["error_message"].format(str(e))
112
+ chat_history.append({"role": "assistant", "content": error_msg})
113
  return chat_history, ""
114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
116
+ current_language = gr.State("en")
 
 
 
 
 
 
117
 
118
+ gr.Markdown(TRANSLATIONS["en"]["title"])
119
+ gr.Markdown(TRANSLATIONS["en"]["description"])
 
120
 
121
  with gr.Group():
122
  chatbot = gr.Chatbot(
123
  value=[],
124
  height=400,
125
+ type="messages" # Use the new messages format
126
  )
127
+
128
+ message = gr.Textbox(
129
+ placeholder=TRANSLATIONS["en"]["message_placeholder"],
130
  lines=3
131
  )
132
 
133
+ with gr.Accordion("Settings", open=False):
134
+ system_message = gr.Textbox(
135
  value=TRANSLATIONS["en"]["system_message"],
136
  label=TRANSLATIONS["en"]["system_message_label"]
137
  )
138
+
139
+ with gr.Row():
140
+ max_tokens = gr.Slider(
141
+ minimum=1,
142
+ maximum=4096,
143
+ value=2048,
144
+ step=1,
145
+ label=TRANSLATIONS["en"]["max_tokens_label"]
146
+ )
147
+ temperature = gr.Slider(
148
+ minimum=0.1,
149
+ maximum=2.0,
150
+ value=0.7,
151
+ step=0.1,
152
+ label=TRANSLATIONS["en"]["temperature_label"]
153
+ )
154
+ top_p = gr.Slider(
155
+ minimum=0.1,
156
+ maximum=1.0,
157
+ value=0.95,
158
+ step=0.05,
159
+ label=TRANSLATIONS["en"]["top_p_label"]
160
+ )
161
+
162
+ with gr.Row():
163
+ language_selector = gr.Radio(
164
+ choices=["en", "pt"],
165
+ value="en",
166
+ label="Language/Idioma",
167
+ interactive=True
168
  )
169
+
170
+ clear = gr.Button("Clear")
171
 
172
+ gr.Markdown(TRANSLATIONS["en"]["info_section"])
 
 
 
 
 
173
 
 
174
  gr.Examples(
175
  examples=TRANSLATIONS["en"]["examples"],
176
+ inputs=message
177
+ )
178
+
179
+ # Event handlers
180
+ message.submit(
181
+ respond,
182
+ [message, chatbot, system_message, max_tokens, temperature, top_p, language_selector],
183
+ [chatbot, message]
184
  )
185
 
186
+ clear.click(lambda: ([], ""), outputs=[chatbot, message])
187
+
188
+ # Update interface text when language changes
189
+ def update_language(lang):
190
+ trans = TRANSLATIONS[lang]
191
+ return (
192
+ trans["message_placeholder"],
193
+ trans["system_message"],
194
+ trans["system_message_label"],
195
+ trans["max_tokens_label"],
196
+ trans["temperature_label"],
197
+ trans["top_p_label"]
198
+ )
199
+
200
+ language_selector.change(
201
+ update_language,
202
+ inputs=[language_selector],
203
  outputs=[
204
+ message,
205
+ system_message,
206
+ system_message, # For label
207
+ max_tokens, # For label
208
+ temperature, # For label
209
+ top_p # For label
 
 
210
  ]
211
  )
212