Untitled conversation
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
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 мин")
Вот исправленный код с учетом всех ваших требований:
import gradio as gr
import os
import shutil
from datetime import datetime
import time
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 # None для очистки file_uploader
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(seconds):
"""
Formats time difference in a human-readable way.
"""
if seconds < 60:
return f"{int(seconds)} сек"
elif seconds < 3600:
minutes = int(seconds / 60)
return f"{minutes} мин"
else:
hours = int(seconds / 3600)
return f"{hours} ч"
def update_timestamp(last_update_time):
"""
Updates the timestamp display.
"""
if last_update_time is None:
return "Готов к загрузке файлов"
current_time = time.time()
time_diff = current_time - last_update_time
return f"Markdown обновлен {format_time_ago(time_diff)} назад"
# 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 last update time
files_state = gr.State([])
last_update_state = 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 under 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="Готов к загрузке файлов",
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] # Добавляем file_uploader в outputs для очистки
).then(
fn=format_file_list,
inputs=files_state,
outputs=file_list
).then(
fn=lambda: time.time(), # Обновляем время последнего обновления
inputs=None,
outputs=last_update_state
)
generate_button.click(
fn=generate_markdown,
inputs=files_state,
outputs=auto_gen
).then(
fn=lambda: time.time(),
inputs=None,
outputs=last_update_state
)
files_state.change(
fn=generate_markdown,
inputs=files_state,
outputs=auto_gen
).then(
fn=lambda: time.time(),
inputs=None,
outputs=last_update_state
)
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: time.time(),
inputs=None,
outputs=last_update_state
)
# Timer для обновления timestamp каждую секунду
timer = gr.Timer(1) # Обновление каждую секунду
timer.tick(
fn=update_timestamp,
inputs=last_update_state,
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()
Основные изменения:
Очистка поля drag and drop: Добавил file_uploader в outputs функции add_files и возвращаю None для его очистки после добавления файлов.
Перемещение кнопки Clear All: Переместил кнопку clear_button сразу после file_list в коде интерфейса.
Обновление времени:
last_update_state для хранения времени последнего обновленияformat_time_ago() для форматирования времени (секунды, минуты, часы)update_timestamp() для обновления отображения времениgr.Timer(1) для автоматического обновления каждую секундуlast_update_state при каждом изменении файлов или генерации markdownТеперь приложение будет: