prithivMLmods commited on
Commit
d9c32c5
1 Parent(s): a494892

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -43
app.py CHANGED
@@ -2,55 +2,94 @@ import os
2
  import gradio as gr
3
  import google.generativeai as genai
4
  from dotenv import load_dotenv
 
5
 
6
- # Custom CSS
7
- css = '''
8
- .gradio-container{max-width: 1000px !important}
9
- h1{text-align:center}
10
- footer {
11
- visibility: hidden
12
- }
13
- '''
14
-
15
  load_dotenv()
16
 
17
- GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
 
18
 
 
19
  genai.configure(api_key=GEMINI_API_KEY)
20
 
21
- def chatbot_response(user_input, mood):
22
-
23
- mood_prompts = {
24
- "Fun": "Respond in a light-hearted, playful manner.",
25
- "Serious": "Respond in a thoughtful, serious tone.",
26
- "Professional": "Respond in a formal, professional manner.",
27
- "Upset": "Respond in a slightly irritated, upset tone."
28
- }
29
-
30
- try:
31
- mood_instruction = mood_prompts.get(mood, "")
32
- prompt = f"{mood_instruction}\n\nUser: {user_input}\nAI:"
33
-
34
- response = genai.generate_text(prompt=prompt)
35
-
36
- reply = response.candidates[0]['text']
37
-
38
- return reply
39
- except Exception as e:
40
- return f"An error occurred: {str(e)}"
41
-
42
- iface = gr.Interface(
43
- fn=chatbot_response,
44
- inputs=[
45
- gr.Textbox(lines=2, placeholder="Enter your message here..."),
46
- gr.Radio(["Fun", "Serious", "Professional", "Upset"], label="Choose the chatbot's mood")
47
- ],
48
- outputs="text",
49
- title="GEMINI GEN",
50
- description=" ",
51
- css=css,
52
- theme="bethecloud/storj_theme",
53
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
 
 
 
 
 
 
 
55
 
56
  iface.launch()
 
2
  import gradio as gr
3
  import google.generativeai as genai
4
  from dotenv import load_dotenv
5
+ import time
6
 
7
+ # Load environment variables from .env file
 
 
 
 
 
 
 
 
8
  load_dotenv()
9
 
10
+ # Retrieve API key from environment variable
11
+ GEMINI_API_KEY = "AIzaSyBRkv6TCfyZtT5Q6H6ur2W8KSNt9ksbeDI" # Public API key
12
 
13
+ # Configure Google Gemini API
14
  genai.configure(api_key=GEMINI_API_KEY)
15
 
16
+ # Create the model configuration
17
+ generation_config = {
18
+ "temperature": 0.7,
19
+ "top_p": 0.95,
20
+ "top_k": 64,
21
+ "max_output_tokens": 512, # Adjust as needed
22
+ "response_mime_type": "text/plain",
23
+ }
24
+
25
+ # Simplified safety settings (or try removing them to test)
26
+ safety_settings = [
27
+ {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
28
+ {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"}
29
+ ]
30
+
31
+ # Define mood prompts
32
+ mood_prompts = {
33
+ "Fun": "Respond in a light-hearted, playful manner.",
34
+ "Serious": "Respond in a thoughtful, serious tone.",
35
+ "Professional": "Respond in a formal, professional manner.",
36
+ "Upset": "Respond in a slightly irritated, upset tone."
37
+ }
38
+
39
+ # Function to generate a response based on user input, chat history, and mood
40
+ def generate_response(user_input, chat_history, mood):
41
+ """Generates a response based on user input, chat history, and mood."""
42
+
43
+ # Update system content with the full character description and mood
44
+ updated_system_content = f"You are Shadow the Hedgehog and you must act like Shadow the Hedgehog's personality. {mood_prompts[mood]}"
45
+
46
+ # Create the generative model
47
+ model = genai.GenerativeModel(
48
+ model_name="gemini-1.5-pro",
49
+ generation_config=generation_config,
50
+ safety_settings=safety_settings,
51
+ system_instruction=updated_system_content,
52
+ )
53
+
54
+ # Add user input to history
55
+ chat_history.append(user_input)
56
+
57
+ # Limit history length to the last 10 messages
58
+ chat_history = chat_history[-10:]
59
+
60
+ retry_attempts = 3
61
+ for attempt in range(retry_attempts):
62
+ try:
63
+ # Start a new chat session
64
+ chat_session = model.start_chat()
65
+
66
+ # Send the entire chat history as the first message
67
+ response = chat_session.send_message("\n".join(chat_history))
68
+ return response.text, chat_history
69
+
70
+ except Exception as e:
71
+ if attempt < retry_attempts - 1:
72
+ time.sleep(2) # Delay before retrying
73
+ continue
74
+ else:
75
+ return f"Error after {retry_attempts} attempts: {str(e)}", chat_history
76
+
77
+ # Build the Gradio interface
78
+ with gr.Blocks(theme="Hev832/Applio") as iface:
79
+ gr.Markdown("Duplicate this space in case there is an error or something with your own Gemini API key!")
80
+ chat_input = gr.Textbox(lines=2, label="Talk to AI", placeholder="Enter your message here...")
81
+ chat_history_state = gr.State([]) # State input for chat history
82
+ response_output = gr.Textbox(label="Response")
83
+
84
+ # Add a dropdown for selecting mood with "Professional" as the default
85
+ mood_selector = gr.Dropdown(choices=list(mood_prompts.keys()), value="Professional", label="Select Mood")
86
 
87
+ # Define the layout and components
88
+ generate_button = gr.Button("Generate Response")
89
+ generate_button.click(
90
+ fn=generate_response,
91
+ inputs=[chat_input, chat_history_state, mood_selector],
92
+ outputs=[response_output, chat_history_state]
93
+ )
94
 
95
  iface.launch()