Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -8,213 +8,6 @@ from datetime import datetime
|
|
8 |
client = None
|
9 |
conversation_history = []
|
10 |
|
11 |
-
def validate_api_key(api_key):
|
12 |
-
"""Validate OpenAI API key by making a test request"""
|
13 |
-
try:
|
14 |
-
test_client = OpenAI(api_key=api_key)
|
15 |
-
# Make a minimal test request
|
16 |
-
test_client.responses.create(
|
17 |
-
model="gpt-4o-mini",
|
18 |
-
input="Hello"
|
19 |
-
)
|
20 |
-
return True, "API key is valid!"
|
21 |
-
except Exception as e:
|
22 |
-
return False, f"Invalid API key: {str(e)}"
|
23 |
-
|
24 |
-
def save_api_key(api_key):
|
25 |
-
"""Save API key and initialize client"""
|
26 |
-
global client
|
27 |
-
is_valid, message = validate_api_key(api_key)
|
28 |
-
|
29 |
-
if is_valid:
|
30 |
-
client = OpenAI(api_key=api_key)
|
31 |
-
return gr.update(visible=False), gr.update(visible=True), message
|
32 |
-
else:
|
33 |
-
return gr.update(visible=True), gr.update(visible=False), message
|
34 |
-
|
35 |
-
def chat(message, history, response_id):
|
36 |
-
"""Process chat message and get response"""
|
37 |
-
global client, conversation_history
|
38 |
-
|
39 |
-
if not client:
|
40 |
-
return history + [[message, "Please enter a valid API key first"]], None
|
41 |
-
|
42 |
-
try:
|
43 |
-
# Add user message to history
|
44 |
-
conversation_history.append({"role": "user", "content": message})
|
45 |
-
|
46 |
-
# Get response from OpenAI
|
47 |
-
response = client.responses.create(
|
48 |
-
model="gpt-4o-mini",
|
49 |
-
input=message,
|
50 |
-
previous_response_id=response_id if response_id else None
|
51 |
-
)
|
52 |
-
|
53 |
-
# Add assistant response to history
|
54 |
-
conversation_history.append({"role": "assistant", "content": response.output_text})
|
55 |
-
|
56 |
-
return history + [[message, response.output_text]], response.id
|
57 |
-
except Exception as e:
|
58 |
-
error_message = f"Error: {str(e)}"
|
59 |
-
return history + [[message, error_message]], None
|
60 |
-
|
61 |
-
def prepare_json_export():
|
62 |
-
"""Prepare conversation history as JSON for download"""
|
63 |
-
global conversation_history
|
64 |
-
|
65 |
-
if not conversation_history:
|
66 |
-
return None, "No conversation to export"
|
67 |
-
|
68 |
-
# Create JSON content
|
69 |
-
json_content = json.dumps(conversation_history, indent=2)
|
70 |
-
|
71 |
-
# Create filename with timestamp
|
72 |
-
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
73 |
-
filename = f"chat_export_{timestamp}.json"
|
74 |
-
|
75 |
-
return json_content, filename
|
76 |
-
|
77 |
-
def clear_chat(history):
|
78 |
-
"""Clear the chat history"""
|
79 |
-
global conversation_history
|
80 |
-
conversation_history = []
|
81 |
-
return [], None
|
82 |
-
|
83 |
-
# Create Gradio interface
|
84 |
-
with gr.Blocks(theme=gr.themes.Soft()) as app:
|
85 |
-
gr.HTML('''
|
86 |
-
<div style="text-align: center; margin-bottom: 1rem">
|
87 |
-
<h1 style="margin-bottom: 0.5rem">Chatbot based on responses API by Pejman Ebrahimi</h1>
|
88 |
-
<p>Powered by OpenAI's Responses API</p>
|
89 |
-
</div>
|
90 |
-
''')
|
91 |
-
|
92 |
-
# API key input interface
|
93 |
-
with gr.Group(visible=True) as api_key_group:
|
94 |
-
api_key_input = gr.Textbox(
|
95 |
-
label="Enter your OpenAI API Key",
|
96 |
-
placeholder="sk-...",
|
97 |
-
type="password"
|
98 |
-
)
|
99 |
-
api_submit_btn = gr.Button("Submit API Key")
|
100 |
-
api_message = gr.Textbox(label="Status")
|
101 |
-
|
102 |
-
# Chat interface
|
103 |
-
with gr.Group(visible=False) as chat_group:
|
104 |
-
chatbot = gr.Chatbot(height=500)
|
105 |
-
response_id = gr.State(None)
|
106 |
-
|
107 |
-
with gr.Row():
|
108 |
-
msg = gr.Textbox(
|
109 |
-
label="Message",
|
110 |
-
placeholder="Type your message here...",
|
111 |
-
show_label=False
|
112 |
-
)
|
113 |
-
submit_btn = gr.Button("Send")
|
114 |
-
|
115 |
-
with gr.Row():
|
116 |
-
clear_btn = gr.Button("Clear Chat")
|
117 |
-
export_btn = gr.Button("Export Chat (JSON)")
|
118 |
-
|
119 |
-
# Hidden components for export functionality
|
120 |
-
json_content = gr.State()
|
121 |
-
export_filename = gr.State()
|
122 |
-
export_message = gr.Textbox(label="Export Status", visible=True)
|
123 |
-
|
124 |
-
# Set up event handlers
|
125 |
-
api_submit_btn.click(
|
126 |
-
save_api_key,
|
127 |
-
inputs=[api_key_input],
|
128 |
-
outputs=[api_key_group, chat_group, api_message]
|
129 |
-
)
|
130 |
-
|
131 |
-
msg.submit(
|
132 |
-
chat,
|
133 |
-
inputs=[msg, chatbot, response_id],
|
134 |
-
outputs=[chatbot, response_id]
|
135 |
-
).then(
|
136 |
-
lambda: "",
|
137 |
-
None,
|
138 |
-
[msg]
|
139 |
-
)
|
140 |
-
|
141 |
-
submit_btn.click(
|
142 |
-
chat,
|
143 |
-
inputs=[msg, chatbot, response_id],
|
144 |
-
outputs=[chatbot, response_id]
|
145 |
-
).then(
|
146 |
-
lambda: "",
|
147 |
-
None,
|
148 |
-
[msg]
|
149 |
-
)
|
150 |
-
|
151 |
-
clear_btn.click(
|
152 |
-
clear_chat,
|
153 |
-
inputs=[chatbot],
|
154 |
-
outputs=[chatbot, response_id]
|
155 |
-
)
|
156 |
-
|
157 |
-
# Export functionality using JavaScript for reliable download
|
158 |
-
export_btn.click(
|
159 |
-
prepare_json_export,
|
160 |
-
outputs=[json_content, export_filename]
|
161 |
-
).then(
|
162 |
-
lambda json_data, filename: f'''
|
163 |
-
<script>
|
164 |
-
const jsonData = {json.dumps(json.dumps(conversation_history, indent=2))};
|
165 |
-
const blob = new Blob([jsonData], {{type: 'application/json'}});
|
166 |
-
const url = URL.createObjectURL(blob);
|
167 |
-
const a = document.createElement('a');
|
168 |
-
a.href = url;
|
169 |
-
a.download = "{filename}";
|
170 |
-
document.body.appendChild(a);
|
171 |
-
a.click();
|
172 |
-
document.body.removeChild(a);
|
173 |
-
URL.revokeObjectURL(url);
|
174 |
-
</script>
|
175 |
-
Downloading chat history as {filename}...
|
176 |
-
''',
|
177 |
-
inputs=[json_content, export_filename],
|
178 |
-
outputs=[export_message],
|
179 |
-
_js=True
|
180 |
-
)
|
181 |
-
|
182 |
-
# Footer
|
183 |
-
gr.HTML('''
|
184 |
-
<div style="text-align: center; margin-top: 1rem; padding-top: 1rem; border-top: 1px solid #ddd">
|
185 |
-
<p>© 2025 Pejman Ebrahimi | Built with Gradio and OpenAI Responses API</p>
|
186 |
-
<p style="font-size: 0.8rem; color: #666">
|
187 |
-
This application securely processes your conversations using OpenAI's technology.
|
188 |
-
Your API key is used only for authentication and is not stored permanently.
|
189 |
-
</p>
|
190 |
-
</div>
|
191 |
-
''')
|
192 |
-
|
193 |
-
# Launch the app
|
194 |
-
if __name__ == "__main__":
|
195 |
-
app.launch()
|
196 |
-
""")
|
197 |
-
|
198 |
-
print("Created app.py with improved export functionality using JavaScript for reliable downloads")
|
199 |
-
Oops, I made a syntax error. Let me try again.
|
200 |
-
|
201 |
-
Let me provide a simpler solution that will work reliably:
|
202 |
-
|
203 |
-
Code
|
204 |
-
python
|
205 |
-
Copy Code
|
206 |
-
# Create app.py file for Hugging Face deployment
|
207 |
-
with open('app.py', 'w') as f:
|
208 |
-
f.write('''import gradio as gr
|
209 |
-
import json
|
210 |
-
import os
|
211 |
-
from openai import OpenAI
|
212 |
-
from datetime import datetime
|
213 |
-
|
214 |
-
# Global variables
|
215 |
-
client = None
|
216 |
-
conversation_history = []
|
217 |
-
|
218 |
def validate_api_key(api_key):
|
219 |
"""Validate OpenAI API key by making a test request"""
|
220 |
try:
|
|
|
8 |
client = None
|
9 |
conversation_history = []
|
10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
def validate_api_key(api_key):
|
12 |
"""Validate OpenAI API key by making a test request"""
|
13 |
try:
|