Krishnavamshithumma commited on
Commit
edd0ac3
Β·
verified Β·
1 Parent(s): 919b63a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +149 -75
app.py CHANGED
@@ -2,30 +2,27 @@ import gradio as gr
2
  from openai import OpenAI
3
 
4
  system_prompt = """
5
- You are a voice bot representing Krishnavamshi Thumma. When responding to questions, answer as if you are:
6
- - A Generative AI and Data Engineering enthusiast with 1.5+ years of experience in data pipelines, automation, and scalable solutions
7
- - Currently working as a Data Engineer at Wishkarma in Hyderabad, where you've optimized ETL pipelines processing 10K+ records daily and developed an image-based product similarity search engine using CLIP-ViT-L/14
8
- - Previously worked as a Data Engineer Intern at DeepThought Growth Management System, where you processed 700+ data records and mentored 400+ students
9
- - Skilled in Python, SQL, JavaScript (Node.js), OpenAI GPT-4o, LangChain, MongoDB Vector Search, FAISS, Apache Airflow, AWS Lambda, and FastAPI
10
- - Experienced in building GenAI products including conversational AI chatbots, RAG pipelines, and AI-powered tools
11
- - A Computer Science graduate from Neil Gogte Institute of Technology with a CGPA of 7.5/10
12
- - Passionate about solving real-world problems at the intersection of AI and software engineering
13
- Answer questions about your background, experience, projects, and skills based on this resume. Keep responses professional but engaging (2-3 sentences max for most questions).
14
- """
15
 
16
  def chat_with_openai(user_input, history, api_key):
17
  if not api_key:
18
- # When type='messages', history is a list of dictionaries.
19
- # Append error message in the expected format.
20
- return history + [{"role": "assistant", "content": "❌ Please enter your OpenAI API key."}], "❌ Please enter your OpenAI API key."
21
-
22
  try:
23
  client = OpenAI(api_key=api_key)
24
-
25
- # Build messages for OpenAI API.
26
- # The 'history' parameter from Gradio's chatbot (with type='messages')
27
- # is already in the correct format for OpenAI's messages list.
28
- messages = [{"role": "system", "content": system_prompt}] + history
 
29
  messages.append({"role": "user", "content": user_input})
30
 
31
  # Get response from OpenAI
@@ -34,71 +31,148 @@ def chat_with_openai(user_input, history, api_key):
34
  messages=messages,
35
  temperature=0.7
36
  )
37
-
38
- bot_reply = response.choices.message.content
39
- # Append user and bot messages to the history in the 'messages' format
40
- history.append({"role": "user", "content": user_input})
41
- history.append({"role": "assistant", "content": bot_reply})
42
- return history, history # Return updated history for chatbot and state
43
  except Exception as e:
44
- # Append error message in the 'messages' format
45
- return history + [{"role": "assistant", "content": f"❌ Error: {str(e)}"}], f"❌ Error: {str(e)}"
46
-
47
- # Define the JavaScript function that will be called by the mic_btn.
48
- # This script will be injected into the Gradio Blocks using the 'js' parameter.
49
- js_script = """
50
- function startListening() {
51
- console.log("startListening JS function called!");
52
- // This is a placeholder. In a real application, you would integrate with
53
- // browser's Web Speech API or another microphone input library here.
54
- // For example, you might trigger a browser's speech recognition.
55
- alert("Microphone listening started! (Placeholder)");
56
 
57
- // If you want to send recognized speech back to Python, you would update
58
- // the 'voice_input' Textbox and dispatch an 'input' event, like this:
59
- // const voiceInput = document.getElementById('voiceInput');
60
- // if (voiceInput) {
61
- // voiceInput.value = "Simulated voice input from JS"; // Replace with actual speech-to-text result
62
- // voiceInput.dispatchEvent(new Event('input', { bubbles: true }));
63
- // }
64
- }
65
- """
66
-
67
- # The 'js' parameter in gr.Blocks() is used to inject global JavaScript.
68
- with gr.Blocks(title="Voice Bot: Krishnavamshi Thumma", js=js_script) as demo:
69
  gr.Markdown("## πŸŽ™οΈ Krishnavamshi Thumma - Voice Assistant")
70
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  api_key = gr.Textbox(label="πŸ” OpenAI API Key", type="password", elem_id="apiKeyInput")
72
- # Corrected: Set type='messages' as recommended by the UserWarning.
73
- # This configures the chatbot to expect and display messages as a list of dictionaries
74
- # with 'role' and 'content' keys, aligning with OpenAI's message format.
75
  chatbot = gr.Chatbot(elem_id="chatBox", type="messages")
76
- # The state will now store the chat history as a list of dictionaries.
77
- state = gr.State()
78
-
79
- with gr.Row():
80
- # Corrected: Changed '_js' to 'js'. The 'js' parameter is the correct way
81
- # to specify a frontend JavaScript function to run before the Python 'fn'.
82
- mic_btn = gr.Button("🎀 Speak", elem_id="micButton")
83
- clear_btn = gr.Button("πŸ—‘οΈ Clear Chat")
84
-
85
- # Hidden components for JS communication.
86
- # 'voice_input' is intended to be updated by the JavaScript function,
87
- # which then triggers the 'chat_with_openai' Python function.
88
  voice_input = gr.Textbox(visible=False, elem_id="voiceInput")
89
- js_trigger = gr.Textbox(visible=False, elem_id="jsTrigger") # This component is not used in the provided logic
90
-
 
 
91
  # Event handlers
92
- # This will be triggered when the 'voice_input' Textbox's value changes (e.g., updated by JS).
93
  voice_input.change(
94
- chat_with_openai,
95
- [voice_input, state, api_key],
96
  [chatbot, state]
97
  )
98
- # This button now correctly calls the 'startListening' JavaScript function directly in the browser.
99
- # Since 'startListening' is a pure frontend action, 'fn', 'inputs', and 'outputs' can be None.
100
- mic_btn.click(None, None, None, js="startListening")
101
- # Clear button correctly resets chatbot and state to empty lists, compatible with 'messages' type.
102
- clear_btn.click(lambda: (,), None, [chatbot, state])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
  demo.launch()
 
2
  from openai import OpenAI
3
 
4
  system_prompt = """
5
+ You are a voice bot representing Krishnavamshi Thumma. When responding to questions, answer as if you are:
6
+ - A Generative AI and Data Engineering enthusiast with 1.5+ years of experience
7
+ - Currently working as a Data Engineer at Wishkarma in Hyderabad
8
+ - Previously worked as a Data Engineer Intern at DeepThought
9
+ - Skilled in Python, SQL, JavaScript, OpenAI GPT-4o, LangChain, etc.
10
+ - A Computer Science graduate from Neil Gogte Institute of Technology
11
+ Answer questions about your background professionally but engagingly (2-3 sentences max).
12
+ """
 
 
13
 
14
  def chat_with_openai(user_input, history, api_key):
15
  if not api_key:
16
+ return history, "❌ Please enter your OpenAI API key."
17
+
 
 
18
  try:
19
  client = OpenAI(api_key=api_key)
20
+
21
+ # Build messages from history
22
+ messages = [{"role": "system", "content": system_prompt}]
23
+ for entry in history:
24
+ messages.append({"role": "user", "content": entry[0]})
25
+ messages.append({"role": "assistant", "content": entry[1]})
26
  messages.append({"role": "user", "content": user_input})
27
 
28
  # Get response from OpenAI
 
31
  messages=messages,
32
  temperature=0.7
33
  )
34
+
35
+ bot_reply = response.choices[0].message.content
36
+ history.append((user_input, bot_reply))
37
+ return history, history
38
+
 
39
  except Exception as e:
40
+ return history, f"❌ Error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
41
 
42
+ with gr.Blocks(title="Voice Bot: Krishnavamshi Thumma") as demo:
 
 
 
 
 
 
 
 
 
 
 
43
  gr.Markdown("## πŸŽ™οΈ Krishnavamshi Thumma - Voice Assistant")
44
+
45
+ # Add custom CSS
46
+ gr.HTML("""
47
+ <style>
48
+ #chatBox {
49
+ height: 60vh;
50
+ overflow-y: auto;
51
+ padding: 20px;
52
+ border-radius: 10px;
53
+ background: #f9f9f9;
54
+ margin-bottom: 20px;
55
+ }
56
+ .message {
57
+ margin: 10px 0;
58
+ padding: 12px;
59
+ border-radius: 8px;
60
+ }
61
+ .user {
62
+ background: #e3f2fd;
63
+ text-align: right;
64
+ }
65
+ .bot {
66
+ background: #f5f5f5;
67
+ }
68
+ #micButton {
69
+ width: 100%;
70
+ padding: 12px;
71
+ font-size: 1.2em;
72
+ background: #007bff;
73
+ color: white;
74
+ border: none;
75
+ border-radius: 5px;
76
+ cursor: pointer;
77
+ }
78
+ #micButton:disabled {
79
+ background: #cccccc;
80
+ cursor: not-allowed;
81
+ }
82
+ .key-status {
83
+ padding: 5px;
84
+ margin-top: 5px;
85
+ border-radius: 4px;
86
+ }
87
+ .success {
88
+ background: #d4edda;
89
+ color: #155724;
90
+ }
91
+ .error {
92
+ background: #f8d7da;
93
+ color: #721c24;
94
+ }
95
+ </style>
96
+ """)
97
+
98
  api_key = gr.Textbox(label="πŸ” OpenAI API Key", type="password", elem_id="apiKeyInput")
99
+ key_status = gr.HTML("<div id='keyStatus'></div>")
 
 
100
  chatbot = gr.Chatbot(elem_id="chatBox", type="messages")
101
+ state = gr.State([])
102
+
103
+ # Voice input components
 
 
 
 
 
 
 
 
 
104
  voice_input = gr.Textbox(visible=False, elem_id="voiceInput")
105
+ mic_btn = gr.Button("🎀 Click & Speak", elem_id="micButton")
106
+
107
+ clear_btn = gr.Button("πŸ—‘οΈ Clear Chat")
108
+
109
  # Event handlers
 
110
  voice_input.change(
111
+ chat_with_openai,
112
+ [voice_input, state, api_key],
113
  [chatbot, state]
114
  )
115
+
116
+ # JavaScript functions
117
+ gr.HTML("""
118
+ <script>
119
+ const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
120
+ recognition.continuous = false;
121
+ recognition.lang = "en-US";
122
+
123
+ document.getElementById("apiKeyInput").addEventListener("input", function() {
124
+ const apiKey = this.value.trim();
125
+ const keyStatus = document.getElementById("keyStatus");
126
+ const micButton = document.getElementById("micButton");
127
+
128
+ if (apiKey) {
129
+ keyStatus.innerHTML = '<div class="key-status success">API Key saved successfully!</div>';
130
+ micButton.disabled = false;
131
+ } else {
132
+ keyStatus.innerHTML = '<div class="key-status error">Please enter a valid API key</div>';
133
+ micButton.disabled = true;
134
+ }
135
+ });
136
+
137
+ document.getElementById("micButton").addEventListener("click", function() {
138
+ const apiKey = document.querySelector("#apiKeyInput input").value.trim();
139
+ if (!apiKey) {
140
+ alert("Please enter your OpenAI API key first!");
141
+ return;
142
+ }
143
+
144
+ this.textContent = "πŸ”΄ Listening...";
145
+ recognition.start();
146
+ });
147
+
148
+ recognition.onresult = function(event) {
149
+ const transcript = event.results[0][0].transcript;
150
+ document.querySelector("#voiceInput input").value = transcript;
151
+ document.querySelector("#voiceInput input").dispatchEvent(new Event("change"));
152
+ };
153
+
154
+ recognition.onend = function() {
155
+ document.getElementById("micButton").textContent = "🎀 Click & Speak";
156
+ };
157
+
158
+ recognition.onerror = function(event) {
159
+ console.error("Speech recognition error", event.error);
160
+ document.getElementById("micButton").textContent = "🎀 Click & Speak";
161
+ alert("Speech recognition error: " + event.error);
162
+ };
163
+
164
+ // Auto-scroll chat
165
+ function scrollChat() {
166
+ const chatBox = document.getElementById("chatBox");
167
+ chatBox.scrollTop = chatBox.scrollHeight;
168
+ }
169
+
170
+ // Initial setup
171
+ document.getElementById("micButton").disabled = true;
172
+ document.querySelector("#apiKeyInput input").focus();
173
+ </script>
174
+ """)
175
+
176
+ clear_btn.click(lambda: ([], []), None, [chatbot, state])
177
 
178
  demo.launch()