|
|
|
|
|
|
|
import os |
|
import time |
|
import pandas as pd |
|
import gradio as gr |
|
from gradio import DeepLinkButton |
|
import pkg_resources |
|
import logging |
|
import glob |
|
from PIL import Image |
|
import fitz |
|
|
|
|
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s") |
|
logger = logging.getLogger(__name__) |
|
log_records = [] |
|
|
|
|
|
class LogCaptureHandler(logging.Handler): |
|
|
|
def emit(self, record): |
|
log_records.append(record) |
|
|
|
logger.addHandler(LogCaptureHandler()) |
|
|
|
|
|
def generate_filename(sequence, ext): |
|
timestamp = time.strftime("%d%m%Y%H%M%S") |
|
return f"{sequence}_{timestamp}.{ext}" |
|
|
|
|
|
def get_gallery_files(file_types): |
|
return sorted(list(set([f for ext in file_types for f in glob.glob(f"*.{ext}")]))) |
|
|
|
|
|
def upload_images(files, history, selected_files): |
|
if not files: |
|
return "No files uploaded", history, selected_files |
|
uploaded = [] |
|
for file in files: |
|
ext = file.name.split('.')[-1].lower() |
|
if ext in ["jpg", "png"]: |
|
output_path = f"img_{int(time.time())}_{os.path.basename(file.name)}" |
|
with open(output_path, "wb") as f: |
|
f.write(file.read()) |
|
uploaded.append(output_path) |
|
history.append(f"Uploaded Image: {output_path}") |
|
selected_files[output_path] = False |
|
return f"Uploaded {len(uploaded)} images", history, selected_files |
|
|
|
|
|
def upload_documents(files, history, selected_files): |
|
if not files: |
|
return "No files uploaded", history, selected_files |
|
uploaded = [] |
|
for file in files: |
|
ext = file.name.split('.')[-1].lower() |
|
if ext in ["pdf"]: |
|
output_path = f"doc_{int(time.time())}_{os.path.basename(file.name)}" |
|
with open(output_path, "wb") as f: |
|
f.write(file.read()) |
|
uploaded.append(output_path) |
|
history.append(f"Uploaded Document: {output_path}") |
|
selected_files[output_path] = False |
|
return f"Uploaded {len(uploaded)} documents", history, selected_files |
|
|
|
|
|
def upload_datasets(files, history, selected_files): |
|
if not files: |
|
return "No files uploaded", history, selected_files |
|
uploaded = [] |
|
for file in files: |
|
ext = file.name.split('.')[-1].lower() |
|
if ext == "csv": |
|
output_path = f"data_{int(time.time())}_{os.path.basename(file.name)}" |
|
with open(output_path, "wb") as f: |
|
f.write(file.read()) |
|
uploaded.append(output_path) |
|
history.append(f"Uploaded Dataset: {output_path}") |
|
selected_files[output_path] = False |
|
return f"Uploaded {len(uploaded)} datasets", history, selected_files |
|
|
|
|
|
def update_galleries(history, selected_files): |
|
galleries = { |
|
"images": get_gallery_files(["jpg", "png"]), |
|
"documents": get_gallery_files(["pdf"]), |
|
"datasets": get_gallery_files(["csv"]), |
|
} |
|
gallery_outputs = { |
|
"images": [(Image.open(f), os.path.basename(f)) for f in galleries["images"]], |
|
"documents": [(Image.frombytes("RGB", fitz.open(f)[0].get_pixmap(matrix=fitz.Matrix(0.5, 0.5)).size, fitz.open(f)[0].get_pixmap(matrix=fitz.Matrix(0.5, 0.5)).samples), os.path.basename(f)) for f in galleries["documents"]], |
|
"datasets": [(f, os.path.basename(f)) for f in galleries["datasets"]], |
|
} |
|
history.append(f"Updated galleries: {sum(len(g) for g in galleries.values())} files") |
|
return gallery_outputs, history, selected_files |
|
|
|
|
|
def update_sidebar(history, selected_files): |
|
all_files = get_gallery_files(["jpg", "png", "pdf", "csv"]) |
|
file_list = [gr.File(label=os.path.basename(f), value=f) for f in all_files] |
|
return file_list, history |
|
|
|
|
|
def toggle_selection(file_list, selected_files): |
|
for file in file_list: |
|
selected_files[file] = not selected_files.get(file, False) |
|
return selected_files |
|
|
|
|
|
def get_dataframe(): |
|
df = pd.DataFrame({ |
|
"Name": ["Alice", "Bob", "Charlie"], |
|
"Age": [25, 30, 35], |
|
"Score": [95.5, 87.0, 92.3] |
|
}) |
|
return df |
|
|
|
|
|
def get_mermaid_chart(): |
|
return """```mermaid |
|
graph TD |
|
A[Upload Files] --> B[View Gallery] |
|
B --> C[Select Files] |
|
C --> D[Generate Output] |
|
D --> E[Deep Link to Result] |
|
```""" |
|
|
|
|
|
def get_code_snippet(): |
|
return "def hello(name):\n return f'Hello, {name}!'" |
|
|
|
|
|
with gr.Blocks(title="Gradio 5.23.0 Mastery Demo 🚀") as demo: |
|
gr.Markdown(f"# Gradio 5.23.0 Mastery Demo 🚀\nRunning Gradio version: {pkg_resources.get_distribution('gradio').version}") |
|
history = gr.State(value=[]) |
|
selected_files = gr.State(value={}) |
|
|
|
with gr.Row(): |
|
with gr.Column(scale=1): |
|
gr.Markdown("## 📁 Files") |
|
sidebar_files = gr.Files(label="Downloads", height=300) |
|
|
|
with gr.Column(scale=3): |
|
with gr.Row(): |
|
gr.Markdown("## 🛠️ Toolbar") |
|
select_btn = gr.Button("✅ Select") |
|
|
|
with gr.Tabs(): |
|
with gr.TabItem("📤 Upload"): |
|
with gr.Row(): |
|
img_upload = gr.File(label="🖼️ Images (jpg/png)", file_count="multiple") |
|
doc_upload = gr.File(label="📜 Docs (pdf)", file_count="multiple") |
|
with gr.Row(): |
|
data_upload = gr.File(label="📊 Data (csv)", file_count="multiple") |
|
upload_status = gr.Textbox(label="Status") |
|
gr.Button("📤 Upload Images").click(upload_images, inputs=[img_upload, history, selected_files], outputs=[upload_status, history, selected_files]).then(update_galleries, inputs=[history, selected_files], outputs=[gr.Gallery(), gr.Gallery(), gr.Gallery(), history, selected_files]).then(update_sidebar, inputs=[history, selected_files], outputs=[sidebar_files, history]) |
|
gr.Button("📤 Upload Docs").click(upload_documents, inputs=[doc_upload, history, selected_files], outputs=[upload_status, history, selected_files]).then(update_galleries, inputs=[history, selected_files], outputs=[gr.Gallery(), gr.Gallery(), gr.Gallery(), history, selected_files]).then(update_sidebar, inputs=[history, selected_files], outputs=[sidebar_files, history]) |
|
gr.Button("📤 Upload Data").click(upload_datasets, inputs=[data_upload, history, selected_files], outputs=[upload_status, history, selected_files]).then(update_galleries, inputs=[history, selected_files], outputs=[gr.Gallery(), gr.Gallery(), gr.Gallery(), history, selected_files]).then(update_sidebar, inputs=[history, selected_files], outputs=[sidebar_files, history]) |
|
|
|
with gr.TabItem("🖼️ Gallery"): |
|
img_gallery = gr.Gallery(label="🖼️ Images (jpg/png)", columns=4, height="auto") |
|
doc_gallery = gr.Gallery(label="📜 Docs (pdf)", columns=4, height="auto") |
|
data_gallery = gr.Gallery(label="📊 Data (csv)", columns=4, height="auto") |
|
gr.Button("🔄 Refresh").click(update_galleries, inputs=[history, selected_files], outputs=[img_gallery, doc_gallery, data_gallery, history, selected_files]).then(update_sidebar, inputs=[history, selected_files], outputs=[sidebar_files, history]) |
|
|
|
with gr.TabItem("🔍 Features"): |
|
gr.Markdown("### 📊 Dataframe Mastery (5.21.0)") |
|
df_output = gr.Dataframe(value=get_dataframe, interactive=True, static_columns=["Name"], wrap=True) |
|
|
|
gr.Markdown("### 📜 Mermaid.js Flowchart (5.23.0)") |
|
mermaid_output = gr.Markdown(value=get_mermaid_chart) |
|
|
|
gr.Markdown("### 🎨 Code Editor with Jedi Completion (5.23.0)") |
|
code_output = gr.Code(value=get_code_snippet, language="python", interactive=True) |
|
|
|
gr.Markdown("### 💥 Deep Link Button (5.23.0)") |
|
DeepLinkButton(label="Link to Latest Output", variant="secondary", deep_link="/gallery/images") |
|
|
|
with gr.TabItem("📜 History"): |
|
history_output = gr.Textbox(label="History", lines=5, value="\n".join(history.value), interactive=False) |
|
|
|
|
|
demo.load(lambda h: "\n".join(h[-5:]), inputs=[history], outputs=[history_output]) |
|
|
|
|
|
demo.launch() |