Update app.py via AI Editor
Browse files166 unmodified lines16716816917017117217399 unmodified lines27327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532640 unmodified lines3673683693703713723731 unmodified line37537637737837938038113 unmodified lines395396397398399400401166 unmodified linesdbc.Col(dbc.Button("Delete",id={'type': 'remove-file', 'index': name},color="danger",size="sm",style={'marginLeft': 'auto', 'float': 'right'}99 unmodified lines@app.callback(Output('file-list', 'children'),[Input('upload-files', 'contents'),Input({'type': 'remove-file', 'index': ALL}, 'n_clicks')],[State('upload-files', 'filename')],prevent_initial_call='initial_duplicate')def handle_file_upload_and_remove(list_of_contents, n_clicks, list_of_names):ctx = callback_contextsession_data, lock = get_session_data()# On first load, restore file list from session temp dirwith lock:restore_session_files(session_data)# If upload triggeredif ctx.triggered and ctx.triggered[0]['prop_id'].startswith("upload-files.contents"):logger.info("Uploading files...")if list_of_contents is not None:with lock:for content, name in zip(list_of_contents, list_of_names):content_type, content_string = content.split(',')decoded = base64.b64decode(content_string)temp_path = os.path.join(session_data['temp_dir'], name)with open(temp_path, 'wb') as f:f.write(decoded)session_data['uploaded_files'][name] = temp_pathsession_data['file_texts'][name] = parse_file_content(temp_path, name)logger.info(f"Files after upload: {list(session_data['uploaded_files'].keys())}")return get_file_cards(session_data['uploaded_files'])# If remove triggeredelif ctx.triggered and "remove-file" in ctx.triggered[0]['prop_id']:triggered_id = ctx.triggered[0]['prop_id'].split('.')[0]import asttry:triggered_id_dict = ast.literal_eval(triggered_id)removed_file = triggered_id_dict['index']except Exception:raise PreventUpdatewith lock:if removed_file in session_data['uploaded_files']:try:os.remove(session_data['uploaded_files'][removed_file])logger.info(f"Deleted file from disk: {removed_file}")except Exception as e:logger.warning(f"Failed to delete temp file {removed_file}: {e}")session_data['uploaded_files'].pop(removed_file, None)session_data['file_texts'].pop(removed_file, None)logger.info(f"Files after deletion: {list(session_data['uploaded_files'].keys())}")return get_file_cards(session_data['uploaded_files'])# Otherwise just display current files (e.g. on initial load)return get_file_cards(session_data['uploaded_files'])def generate_matrix_with_gpt(matrix_type, file_contents):prompt = f"""Generate a {matrix_type} based on the following project artifacts:40 unmodified linesdef handle_matrix_and_chat(*args):session_data, lock = get_session_data()ctx = callback_context# Matrix generation button pressedmatrix_btns_len = len(matrix_types)matrix_btn_inputs = args[:matrix_btns_len]chat_n_clicks = args[matrix_btns_len]1 unmodified lineif not ctx.triggered:raise PreventUpdatetriggered_id = ctx.triggered[0]['prop_id'].split('.')[0]# If matrix button triggeredif "matrix-btn" in triggered_id:import asttry:13 unmodified linesexcept Exception as e:logger.exception(f"Error generating matrix: {str(e)}")return html.Div(f"Error generating matrix: {str(e)}"), "Error", ""# If chat send button triggeredelif "btn-send-chat" in triggered_id:if not chat_input_value or session_data['current_matrix'] is None or session_data['matrix_type'] is None:raise PreventUpdate166 unmodified lines16716816917017117217399 unmodified lines27327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133240 unmodified lines3733743753763773781 unmodified line38038138238338438513 unmodified lines399400401402403404166 unmodified linesdbc.Col(dbc.Button("Delete",id={'type': 'delete-file-btn', 'index': name},color="danger",size="sm",style={'marginLeft': 'auto', 'float': 'right'}99 unmodified lines@app.callback(Output('file-list', 'children'),[Input('upload-files', 'contents'),Input({'type': 'delete-file-btn', 'index': ALL}, 'n_clicks')],[State('upload-files', 'filename'),],prevent_initial_call='initial_duplicate')def handle_file_upload_and_delete(list_of_contents, delete_clicks, list_of_names):ctx = callback_contextsession_data, lock = get_session_data()with lock:restore_session_files(session_data)triggered = ctx.triggeredif triggered:prop_id = triggered[0]['prop_id']# Handle file uploadif prop_id.startswith("upload-files.contents"):logger.info("Uploading files...")if list_of_contents is not None and list_of_names is not None:for content, name in zip(list_of_contents, list_of_names):content_type, content_string = content.split(',')decoded = base64.b64decode(content_string)temp_path = os.path.join(session_data['temp_dir'], name)with open(temp_path, 'wb') as f:f.write(decoded)session_data['uploaded_files'][name] = temp_pathsession_data['file_texts'][name] = parse_file_content(temp_path, name)logger.info(f"Files after upload: {list(session_data['uploaded_files'].keys())}")return get_file_cards(session_data['uploaded_files'])# Handle delete button clickelif "delete-file-btn" in prop_id:import astbtn_id = prop_id.split('.')[0]try:btn_id_dict = ast.literal_eval(btn_id)filename = btn_id_dict['index']except Exception as e:logger.warning(f"Could not extract filename from delete prop_id: {prop_id} error: {e}")raise PreventUpdateif filename in session_data['uploaded_files']:filepath = session_data['uploaded_files'][filename]try:os.remove(filepath)logger.info(f"Deleted file from disk: {filename}")except Exception as e:logger.warning(f"Failed to delete temp file {filename}: {e}")session_data['uploaded_files'].pop(filename, None)session_data['file_texts'].pop(filename, None)logger.info(f"Files after deletion: {list(session_data['uploaded_files'].keys())}")return get_file_cards(session_data['uploaded_files'])# On initial load or no trigger, show files from sessionreturn get_file_cards(session_data['uploaded_files'])def generate_matrix_with_gpt(matrix_type, file_contents):prompt = f"""Generate a {matrix_type} based on the following project artifacts:40 unmodified linesdef handle_matrix_and_chat(*args):session_data, lock = get_session_data()ctx = callback_contextmatrix_btns_len = len(matrix_types)matrix_btn_inputs = args[:matrix_btns_len]chat_n_clicks = args[matrix_btns_len]1 unmodified lineif not ctx.triggered:raise PreventUpdatetriggered_id = ctx.triggered[0]['prop_id'].split('.')[0]if "matrix-btn" in triggered_id:import asttry:13 unmodified linesexcept Exception as e:logger.exception(f"Error generating matrix: {str(e)}")return html.Div(f"Error generating matrix: {str(e)}"), "Error", ""elif "btn-send-chat" in triggered_id:if not chat_input_value or session_data['current_matrix'] is None or session_data['matrix_type'] is None:raise PreventUpdate
app.py+46-43