```
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 мин")