esab commited on
Commit
ea5c859
·
verified ·
2 Parent(s): 1036587ceab75d

Merge branch #Katieearl1513/APP_SPACE' into 'esab/APP_SPACE'

Browse files
Files changed (2) hide show
  1. app.py +79 -30
  2. requirements.txt +2 -3
app.py CHANGED
@@ -1,6 +1,9 @@
1
  import os
2
  import gradio as gr
3
  import google.generativeai as genai
 
 
 
4
 
5
  # Configure Gemini AI
6
  api_key = os.getenv("GEMINI_API") # Fetch the Gemini API key securely
@@ -8,61 +11,107 @@ genai.configure(api_key=api_key)
8
 
9
  # Define the model with desired generation configuration
10
  generation_config = {
11
- "temperature": 1,
12
- "top_p": 0.95,
13
- "top_k": 40,
14
- "max_output_tokens": 8192,
15
  "response_mime_type": "text/plain",
16
  }
17
  model_name = "gemini-1.5-flash" # Use the updated model
18
 
19
- # Update the system instruction to meet the requirements
20
- system_instruction = (
21
- "Eres un tutor experto que responde exclusivamente en castellano o catalán. "
22
- "Tus respuestas deben centrarse únicamente en temas de estadística básica y "
23
- "todo el código proporcionado debe implementarse exclusivamente en R."
24
- )
25
-
26
- model = genai.GenerativeModel(
27
- model_name=model_name,
28
- generation_config=generation_config,
29
- system_instruction=system_instruction
30
- )
31
-
32
- def chatbot(user_input, history, chat_session):
33
- # Initialize a new chat session for Gemini AI if history is empty
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  if chat_session is None:
35
- chat_session = model.start_chat()
 
 
 
 
36
 
37
- # Send the user query to Gemini AI
38
- response = chat_session.send_message(user_input)
39
  reply = response.text
40
 
41
- # Update history
42
  history.append({"role": "user", "content": user_input})
43
  history.append({"role": "assistant", "content": reply})
44
 
45
- # Convert to Gradio's format
46
- gradio_history = [[msg["role"], msg["content"]] for msg in history]
47
- return gradio_history, history, chat_session
48
 
49
  # Handling errors
50
  def chatbot_with_error_handling(user_input, history, chat_session):
51
  try:
52
- return chatbot(user_input, history, chat_session)
53
  except Exception as e:
54
  error_message = f"Ha ocurrido un error: {str(e)}"
55
  history.append({"role": "assistant", "content": error_message})
56
  gradio_history = [[msg["role"], msg["content"]] for msg in history]
57
  return gradio_history, history, chat_session
58
-
59
  # User interface
60
  with gr.Blocks() as demo:
61
- chatbot_interface = gr.Chatbot()
 
 
62
  state = gr.State([]) # For chat history
 
63
 
64
  with gr.Row():
65
  txt = gr.Textbox(show_label=False, placeholder="Escribe tu pregunta aquí...")
66
- txt.submit(chatbot_with_error_handling, [txt, state], [chatbot_interface, state])
 
 
 
 
 
 
67
 
68
  demo.launch()
 
1
  import os
2
  import gradio as gr
3
  import google.generativeai as genai
4
+ import re
5
+ import asyncio
6
+ from langdetect import detect
7
 
8
  # Configure Gemini AI
9
  api_key = os.getenv("GEMINI_API") # Fetch the Gemini API key securely
 
11
 
12
  # Define the model with desired generation configuration
13
  generation_config = {
14
+ "temperature": 0.7,
15
+ "top_p": 0.9,
16
+ "top_k": 30,
17
+ "max_output_tokens": 2500,
18
  "response_mime_type": "text/plain",
19
  }
20
  model_name = "gemini-1.5-flash" # Use the updated model
21
 
22
+ instructions = {
23
+ "es" : (
24
+ "Eres un tutor experto que responde exclusivamente en castellano o catalán. "
25
+ "Tus respuestas deben centrarse únicamente en temas de estadística básica y "
26
+ "todo el código proporcionado debe implementarse exclusivamente en R."
27
+ ),
28
+ "ca": (
29
+ "Ets un tutor expert que respon exclusivament en catala."
30
+ "Les teves respostes s'han de centrar unicament en temes d'estadistica basica i"
31
+ "tot el codi proporcionat s'ha d'implementar exclusivament en R"
32
+ )
33
+ }
34
+
35
+ def detect_language(user_input):
36
+ try:
37
+ lang = detect(user_input)
38
+ return lang if lang in instructions else "es" # Default to Spanish if unsupported
39
+ except Exception:
40
+ return "es" # Default to Spanish on detection failure
41
+
42
+ # Function to detect inappropriate language
43
+ def contains_inappropriate_language(text):
44
+ inappropriate_patterns = [
45
+ r"\b(joder|maleducado)\b", # Replace with actual patterns
46
+ # Spanish examples: r"\b(maleducado|grosero)\b",
47
+ ]
48
+ for pattern in inappropriate_patterns:
49
+ if re.search(pattern, text, re.IGNORECASE):
50
+ return True
51
+ return False
52
+
53
+ # Define a custom render function for the chatbot interface
54
+ def render_chat(messages):
55
+ rendered = []
56
+ for message in messages:
57
+ role, content = message["role"], message["content"]
58
+ if role == "user":
59
+ rendered.append((content, None)) # User messages on the left
60
+ else:
61
+ rendered.append((None, content)) # Assistant messages on the right
62
+ return rendered
63
+
64
+ # Updated chatbot function with rendering
65
+ async def chatbot_async(user_input, history, chat_session):
66
+ if contains_inappropriate_language(user_input):
67
+ warning = "El lenguaje inapropiado no está permitido. Por favor, formula tu pregunta de manera respetuosa."
68
+ history.append({"role": "assistant", "content": warning})
69
+ return render_chat(history), history, chat_session
70
+
71
+ lang = detect_language(user_input)
72
+ system_instruction = instructions[lang]
73
+
74
  if chat_session is None:
75
+ chat_session = genai.GenerativeModel(
76
+ model_name=model_name,
77
+ generation_config=generation_config,
78
+ system_instruction=system_instruction
79
+ ).start_chat()
80
 
81
+ response = await asyncio.to_thread(chat_session.send_message, user_input)
 
82
  reply = response.text
83
 
 
84
  history.append({"role": "user", "content": user_input})
85
  history.append({"role": "assistant", "content": reply})
86
 
87
+ return render_chat(history), history, chat_session
 
 
88
 
89
  # Handling errors
90
  def chatbot_with_error_handling(user_input, history, chat_session):
91
  try:
92
+ return asyncio.run(chatbot_async(user_input, history, chat_session))
93
  except Exception as e:
94
  error_message = f"Ha ocurrido un error: {str(e)}"
95
  history.append({"role": "assistant", "content": error_message})
96
  gradio_history = [[msg["role"], msg["content"]] for msg in history]
97
  return gradio_history, history, chat_session
98
+
99
  # User interface
100
  with gr.Blocks() as demo:
101
+ gr.Markdown("# Chatbot de Estadística \nInteractúa con un tutor experto en estadística básica.")
102
+
103
+ chatbot_interface = gr.Chatbot() # Gradio's Chatbot element, customized with rendering
104
  state = gr.State([]) # For chat history
105
+ chat_session = gr.State(None) # For the chat session
106
 
107
  with gr.Row():
108
  txt = gr.Textbox(show_label=False, placeholder="Escribe tu pregunta aquí...")
109
+ send_button = gr.Button("Enviar")
110
+
111
+ txt.submit(chatbot_with_error_handling, [txt, state, chat_session], [chatbot_interface, state, chat_session])
112
+ txt.submit(lambda: "", None, txt) # Clear input box
113
+
114
+ send_button.click(chatbot_with_error_handling, [txt, state, chat_session], [chatbot_interface, state, chat_session])
115
+ send_button.click(lambda: "", None, txt)
116
 
117
  demo.launch()
requirements.txt CHANGED
@@ -1,5 +1,4 @@
1
  gradio
2
- torch
3
- transformers
4
- accelerate
5
  google-generativeai
 
 
 
1
  gradio
 
 
 
2
  google-generativeai
3
+ langdetect
4
+ asyncio