Untitled conversation
- User
import gradio as gr import os import shutil from datetime import datetime def add_files(current_files, new_files): """ Adds new files to the current list of files. """ if not current_files: current_files = [] if not new_files: return current_files, "Please upload files to add to the list" # Create temp directory if it doesn't exist temp_dir = "temp_files" if not os.path.exists(temp_dir): os.makedirs(temp_dir) new_file_list = [] for file_path in new_files: filename = os.path.basename(file_path) timestamp = datetime.now().strftime("%Y%m%d%H%M%S") unique_filename = f"{timestamp}_{filename}" dest_path = os.path.join(temp_dir, unique_filename) shutil.copy2(file_path, dest_path) new_file_list.append({ "original_name": filename, "path": dest_path, "size": os.path.getsize(dest_path) }) updated_files = current_files + new_file_list message = f"Added {len(new_file_list)} files. Total files: {len(updated_files)}" return updated_files, message def clear_files(files): """ Clears all files from the list. """ if not files: return [], "File list is already empty" for file in files: if os.path.exists(file["path"]): os.remove(file["path"]) return [], "All files removed" def generate_markdown(files): """ Generates Markdown from the list of files. """ if not files: return "Please upload at least one file" markdown_parts = [] for file in files: try: filename = file["original_name"] filepath = file["path"] with open(filepath, 'r', encoding='utf-8') as f: content = f.read() file_block = f"```{filename}\n{content}\n```" markdown_parts.append(file_block) except Exception as e: filename = file["original_name"] markdown_parts.append(f"```\nError reading file {filename}:\n{e}\n```") all_blocks = "\n".join(markdown_parts) final_markdown = f"{all_blocks}\n\n---\n" return final_markdown def format_file_list(files): """ Formats the list of files for display. """ if not files: return [] formatted_list = [] for i, file in enumerate(files): size_kb = file["size"] / 1024 if size_kb < 1024: size_str = f"{size_kb:.2f} KB" else: size_mb = size_kb / 1024 size_str = f"{size_mb:.2f} MB" formatted_list.append([i, file["original_name"], size_str]) return formatted_list # Create the interface with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown( """ # Markdown Generator from Code Files Upload files and generate Markdown documents. You can gradually add new files and manage the list. """ ) # State for file list files_state = gr.State([]) # File upload component file_uploader = gr.File( label="Drag and drop files here", file_count="multiple", type="filepath" ) # Add button below the file upload add_button = gr.Button("Add Files", variant="primary") # File list table file_list = gr.Dataframe( headers=["#", "File Name", "Size"], label="Uploaded Files", row_count=10, col_count=(3, "fixed"), interactive=False ) # Auto-generate markdown on file change auto_gen = gr.Textbox( label="Generated Markdown", lines=20, interactive=False, show_copy_button=True ) # Manual generate button generate_button = gr.Button("Generate Markdown", variant="primary", size="lg") # Timestamp display timestamp = gr.Textbox( label="Last Update", value="Markdown was updated 0 seconds ago", interactive=False ) # Status message (hidden by default) status_message = gr.Textbox( label="Status", value="Ready to upload files", interactive=False, visible=False ) # Event handlers add_button.click( fn=add_files, inputs=[files_state, file_uploader], outputs=[files_state, status_message] ).then( fn=format_file_list, inputs=files_state, outputs=file_list ).then( fn=lambda: "Markdown was updated 0 seconds ago", inputs=None, outputs=timestamp ) generate_button.click( fn=generate_markdown, inputs=files_state, outputs=auto_gen ).then( fn=lambda: "Markdown was updated 0 seconds ago", inputs=None, outputs=timestamp ) files_state.change( fn=generate_markdown, inputs=files_state, outputs=auto_gen ).then( fn=lambda: "Markdown was updated 0 seconds ago", inputs=None, outputs=timestamp ) clear_button = gr.Button("Clear All", variant="stop") clear_button.click( fn=clear_files, inputs=files_state, outputs=[files_state, status_message] ).then( fn=format_file_list, inputs=files_state, outputs=file_list ).then( fn=lambda: "Markdown was updated 0 seconds ago", inputs=None, outputs=timestamp ) # Initialize file list demo.load( fn=lambda: [], inputs=None, outputs=file_list ) if __name__ == "__main__": if not os.path.exists("temp_files"): os.makedirs("temp_files") demo.launch()
1 после нажатия на add files, ОЧИЩАЙ поле для drag and drop 2 кнопка clear all, сделай прямо под списком файлов для markdown 3 проблема - статус "обновлено XXX назад", не обновляется со временем (а должен каждую секунду. +с форматирвоанием по типу, "4 мин")
Assistant
I'll address each of your requested changes to the Gradio application:
import gradio as gr import os import shutil import time from datetime import datetime def add_files(current_files, new_files): """ Adds new files to the current list of files. """ if not current_files: current_files = [] if not new_files: return current_files, "Please upload files to add to the list", None # Create temp directory if it doesn't exist temp_dir = "temp_files" if not os.path.exists(temp_dir): os.makedirs(temp_dir) new_file_list = [] for file_path in new_files: filename = os.path.basename(file_path) timestamp = datetime.now().strftime("%Y%m%d%H%M%S") unique_filename = f"{timestamp}_{filename}" dest_path = os.path.join(temp_dir, unique_filename) shutil.copy2(file_path, dest_path) new_file_list.append({ "original_name": filename, "path": dest_path, "size": os.path.getsize(dest_path) }) updated_files = current_files + new_file_list message = f"Added {len(new_file_list)} files. Total files: {len(updated_files)}" return updated_files, message, None # Return None to clear the file upload field def clear_files(files): """ Clears all files from the list. """ if not files: return [], "File list is already empty" for file in files: if os.path.exists(file["path"]): os.remove(file["path"]) return [], "All files removed" def generate_markdown(files): """ Generates Markdown from the list of files. """ if not files: return "Please upload at least one file" markdown_parts = [] for file in files: try: filename = file["original_name"] filepath = file["path"] with open(filepath, 'r', encoding='utf-8') as f: content = f.read() file_block = f"```{filename}\n{content}\n```" markdown_parts.append(file_block) except Exception as e: filename = file["original_name"] markdown_parts.append(f"```\nError reading file {filename}:\n{e}\n```") all_blocks = "\n".join(markdown_parts) final_markdown = f"{all_blocks}\n\n---\n" return final_markdown def format_file_list(files): """ Formats the list of files for display. """ if not files: return [] formatted_list = [] for i, file in enumerate(files): size_kb = file["size"] / 1024 if size_kb < 1024: size_str = f"{size_kb:.2f} KB" else: size_mb = size_kb / 1024 size_str = f"{size_mb:.2f} MB" formatted_list.append([i, file["original_name"], size_str]) return formatted_list def format_time_ago(): """ Returns the current timestamp for the update message. """ return int(time.time()) def update_timestamp(last_update_time): """ Updates the timestamp display with a human-readable format. """ if not last_update_time: return "Markdown was updated just now" seconds_ago = int(time.time() - last_update_time) if seconds_ago < 60: return f"Markdown was updated {seconds_ago} seconds ago" elif seconds_ago < 3600: minutes = seconds_ago // 60 return f"Markdown was updated {minutes} min ago" elif seconds_ago < 86400: hours = seconds_ago // 3600 return f"Markdown was updated {hours} hours ago" else: days = seconds_ago // 86400 return f"Markdown was updated {days} days ago" # Create the interface with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown( """ # Markdown Generator from Code Files Upload files and generate Markdown documents. You can gradually add new files and manage the list. """ ) # State for file list and timestamp files_state = gr.State([]) last_update_time = gr.State(None) # File upload component file_uploader = gr.File( label="Drag and drop files here", file_count="multiple", type="filepath" ) # Add button below the file upload add_button = gr.Button("Add Files", variant="primary") # File list table file_list = gr.Dataframe( headers=["#", "File Name", "Size"], label="Uploaded Files", row_count=10, col_count=(3, "fixed"), interactive=False ) # Clear button right below the file list clear_button = gr.Button("Clear All", variant="stop") # Auto-generate markdown on file change auto_gen = gr.Textbox( label="Generated Markdown", lines=20, interactive=False, show_copy_button=True ) # Manual generate button generate_button = gr.Button("Generate Markdown", variant="primary", size="lg") # Timestamp display timestamp = gr.Textbox( label="Last Update", value="Markdown was updated 0 seconds ago", interactive=False ) # Status message (hidden by default) status_message = gr.Textbox( label="Status", value="Ready to upload files", interactive=False, visible=False ) # Event handlers add_button.click( fn=add_files, inputs=[files_state, file_uploader], outputs=[files_state, status_message, file_uploader] # Added file_uploader to clear it ).then( fn=format_file_list, inputs=files_state, outputs=file_list ).then( fn=format_time_ago, inputs=None, outputs=last_update_time ).then( fn=update_timestamp, inputs=last_update_time, outputs=timestamp ) generate_button.click( fn=generate_markdown, inputs=files_state, outputs=auto_gen ).then( fn=format_time_ago, inputs=None, outputs=last_update_time ).then( fn=update_timestamp, inputs=last_update_time, outputs=timestamp ) files_state.change( fn=generate_markdown, inputs=files_state, outputs=auto_gen ).then( fn=format_time_ago, inputs=None, outputs=last_update_time ).then( fn=update_timestamp, inputs=last_update_time, outputs=timestamp ) clear_button.click( fn=clear_files, inputs=files_state, outputs=[files_state, status_message] ).then( fn=format_file_list, inputs=files_state, outputs=file_list ).then( fn=format_time_ago, inputs=None, outputs=last_update_time ).then( fn=update_timestamp, inputs=last_update_time, outputs=timestamp ) # Initialize file list demo.load( fn=lambda: [], inputs=None, outputs=file_list ) # Update timestamp every second demo.load( fn=lambda: 1, inputs=None, outputs=gr.Number(visible=False), every=1 ).then( fn=update_timestamp, inputs=last_update_time, outputs=timestamp ) if __name__ == "__main__": if not os.path.exists("temp_files"): os.makedirs("temp_files") demo.launch()Would you like me to explain or break down the changes I made?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.