Spaces:
Runtime error
Runtime error
Update app.py
Browse files7 unmodified lines891011121345 unmodified lines596061626364656667686970717273747576777837 unmodified lines11611711811912012112212312430 unmodified lines1551561571581591601611621631641659 unmodified lines1751761771781791807 unmodified linesclient = Noneconversation_history = []def validate_api_key(api_key):"""Validate OpenAI API key by making a test request"""try:45 unmodified linesreturn history + [[message, error_message]], Nonedef export_chat():"""Export conversation history to JSON file for download"""global conversation_historyif not conversation_history:return None, "No conversation to export"timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")filename = f"chat_export_{timestamp}.json"# Create JSON contentjson_content = json.dumps(conversation_history, indent=2)# Return file for download and status messagereturn (filename, json_content), f"Conversation ready for download"def clear_chat(history):"""Clear the chat history"""37 unmodified linesclear_btn = gr.Button("Clear Chat")export_btn = gr.Button("Export Chat (JSON)")# File download componentchat_file = gr.File(label="Download Chat", visible=False)export_message = gr.Textbox(label="Export Status", visible=True)# Set up event handlersapi_submit_btn.click(30 unmodified linesexport_btn.click(export_chat,outputs=[chat_file, export_message]).then(lambda: gr.update(visible=True),None,[chat_file])# Footer9 unmodified lines# Launch the appif __name__ == "__main__":app.launch()print("Updated Gradio app code with downloadable JSON export functionality.")7 unmodified lines8910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922045 unmodified lines26626726826927027127227327427527627727827928028128228328428528637 unmodified lines32432532632732832933033133230 unmodified lines3633643653663673683699 unmodified lines3793803813827 unmodified linesclient = Noneconversation_history = []def validate_api_key(api_key):"""Validate OpenAI API key by making a test request"""try:test_client = OpenAI(api_key=api_key)# Make a minimal test requesttest_client.responses.create(model="gpt-4o-mini",input="Hello")return True, "API key is valid!"except Exception as e:return False, f"Invalid API key: {str(e)}"def save_api_key(api_key):"""Save API key and initialize client"""global clientis_valid, message = validate_api_key(api_key)if is_valid:client = OpenAI(api_key=api_key)return gr.update(visible=False), gr.update(visible=True), messageelse:return gr.update(visible=True), gr.update(visible=False), messagedef chat(message, history, response_id):"""Process chat message and get response"""global client, conversation_historyif not client:return history + [[message, "Please enter a valid API key first"]], Nonetry:# Add user message to historyconversation_history.append({"role": "user", "content": message})# Get response from OpenAIresponse = client.responses.create(model="gpt-4o-mini",input=message,previous_response_id=response_id if response_id else None)# Add assistant response to historyconversation_history.append({"role": "assistant", "content": response.output_text})return history + [[message, response.output_text]], response.idexcept Exception as e:error_message = f"Error: {str(e)}"return history + [[message, error_message]], Nonedef prepare_json_export():"""Prepare conversation history as JSON for download"""global conversation_historyif not conversation_history:return None, "No conversation to export"# Create JSON contentjson_content = json.dumps(conversation_history, indent=2)# Create filename with timestamptimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")filename = f"chat_export_{timestamp}.json"return json_content, filenamedef clear_chat(history):"""Clear the chat history"""global conversation_historyconversation_history = []return [], None# Create Gradio interfacewith gr.Blocks(theme=gr.themes.Soft()) as app:gr.HTML('''<div style="text-align: center; margin-bottom: 1rem"><h1 style="margin-bottom: 0.5rem">Chatbot based on responses API by Pejman Ebrahimi</h1><p>Powered by OpenAI's Responses API</p></div>''')# API key input interfacewith gr.Group(visible=True) as api_key_group:api_key_input = gr.Textbox(label="Enter your OpenAI API Key",placeholder="sk-...",type="password")api_submit_btn = gr.Button("Submit API Key")api_message = gr.Textbox(label="Status")# Chat interfacewith gr.Group(visible=False) as chat_group:chatbot = gr.Chatbot(height=500)response_id = gr.State(None)with gr.Row():msg = gr.Textbox(label="Message",placeholder="Type your message here...",show_label=False)submit_btn = gr.Button("Send")with gr.Row():clear_btn = gr.Button("Clear Chat")export_btn = gr.Button("Export Chat (JSON)")# Hidden components for export functionalityjson_content = gr.State()export_filename = gr.State()export_message = gr.Textbox(label="Export Status", visible=True)# Set up event handlersapi_submit_btn.click(save_api_key,inputs=[api_key_input],outputs=[api_key_group, chat_group, api_message])msg.submit(chat,inputs=[msg, chatbot, response_id],outputs=[chatbot, response_id]).then(lambda: "",None,[msg])submit_btn.click(chat,inputs=[msg, chatbot, response_id],outputs=[chatbot, response_id]).then(lambda: "",None,[msg])clear_btn.click(clear_chat,inputs=[chatbot],outputs=[chatbot, response_id])# Export functionality using JavaScript for reliable downloadexport_btn.click(prepare_json_export,outputs=[json_content, export_filename]).then(lambda json_data, filename: f'''<script>const jsonData = {json.dumps(json.dumps(conversation_history, indent=2))};const blob = new Blob([jsonData], {{type: 'application/json'}});const url = URL.createObjectURL(blob);const a = document.createElement('a');a.href = url;a.download = "{filename}";document.body.appendChild(a);a.click();document.body.removeChild(a);URL.revokeObjectURL(url);</script>Downloading chat history as {filename}...''',inputs=[json_content, export_filename],outputs=[export_message],_js=True)# Footergr.HTML('''<div style="text-align: center; margin-top: 1rem; padding-top: 1rem; border-top: 1px solid #ddd"><p>© 2025 Pejman Ebrahimi | Built with Gradio and OpenAI Responses API</p><p style="font-size: 0.8rem; color: #666">This application securely processes your conversations using OpenAI's technology.Your API key is used only for authentication and is not stored permanently.</p></div>''')# Launch the appif __name__ == "__main__":app.launch()""")print("Created app.py with improved export functionality using JavaScript for reliable downloads")Oops, I made a syntax error. Let me try again.Let me provide a simpler solution that will work reliably:CodepythonCopy Code# Create app.py file for Hugging Face deploymentwith open('app.py', 'w') as f:f.write('''import gradio as grimport jsonimport osfrom openai import OpenAIfrom datetime import datetime# Global variablesclient = Noneconversation_history = []def validate_api_key(api_key):"""Validate OpenAI API key by making a test request"""try:45 unmodified linesreturn history + [[message, error_message]], Nonedef export_chat():"""Export conversation history as downloadable JSON"""global conversation_historyif not conversation_history:return None, "No conversation to export"# Create filename with timestamptimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")filename = f"chat_export_{timestamp}.json"# Create JSON contentjson_content = json.dumps(conversation_history, indent=2)# Return file for downloadreturn (filename, json_content), "Chat exported successfully. Download should start automatically."def clear_chat(history):"""Clear the chat history"""37 unmodified linesclear_btn = gr.Button("Clear Chat")export_btn = gr.Button("Export Chat (JSON)")# File download component and status messagefile_output = gr.File(label="Download Chat")export_message = gr.Textbox(label="Export Status")# Set up event handlersapi_submit_btn.click(30 unmodified linesexport_btn.click(export_chat,outputs=[file_output, export_message])# Footer9 unmodified lines# Launch the appif __name__ == "__main__":app.launch()
app.py+216-14