File size: 10,880 Bytes
614ef28
 
 
 
 
 
 
 
 
3966f89
1a2a001
 
 
3966f89
 
 
 
614ef28
 
 
 
 
 
3966f89
1a2a001
3966f89
 
1a2a001
3966f89
1a2a001
3966f89
1a2a001
3966f89
 
 
1a2a001
3966f89
1a2a001
191766c
1a2a001
3966f89
 
1a2a001
3966f89
1a2a001
3966f89
1a2a001
191766c
 
1a2a001
191766c
 
1a2a001
191766c
1a2a001
3966f89
1a2a001
191766c
1a2a001
 
191766c
3966f89
1a2a001
191766c
 
1a2a001
191766c
 
1a2a001
614ef28
1a2a001
191766c
1a2a001
191766c
1a2a001
 
191766c
 
614ef28
191766c
 
1a2a001
191766c
 
1a2a001
614ef28
1a2a001
191766c
1a2a001
191766c
1a2a001
 
191766c
 
1a2a001
3966f89
 
1a2a001
614ef28
 
3966f89
 
1a2a001
614ef28
1a2a001
3966f89
1a2a001
3966f89
 
1a2a001
191766c
614ef28
 
191766c
 
1a2a001
3966f89
 
1a2a001
3966f89
 
614ef28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3966f89
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
Apologies for the breakup! Here’s the complete, unbroken code listing for app.py, incorporating the Gradio 5.23.0 features demo without the accept parameter, all in one cohesive block:

python

Collapse

Wrap

Copy
#!/usr/bin/env python3
# 😂 Shebangin’ it like it’s 1999—Python 3, let’s roll!

# 🧳 Importing the whole circus—get ready for a wild ride!
import os
import time
import pandas as pd
import gradio as gr
from gradio import DeepLinkButton  # 🔥 Deep links from 5.23.0!
import pkg_resources  # 🕵️‍♂️ Sneaky version checker!
import logging
import glob
from PIL import Image
import fitz

# 📜 Logging setup—because even AIs need a diary!
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)
log_records = []  # 🗒️ Dear diary, today I logged a thing...

# 🤓 LogCaptureHandler class—catching logs like a pro fisherman!
class LogCaptureHandler(logging.Handler):
    # 🎣 Hooking those logs right outta the stream!
    def emit(self, record):
        log_records.append(record)

logger.addHandler(LogCaptureHandler())  # 🐟 Adding the hook to the logger—catch ‘em all!

# 😂 Time to stamp files like a boss—unique names incoming!
def generate_filename(sequence, ext):
    timestamp = time.strftime("%d%m%Y%H%M%S")  # ⏰ Clock says “name me now!”
    return f"{sequence}_{timestamp}.{ext}"

# 🕵️‍♂️ Sherlocking the filesystem for your precious files!
def get_gallery_files(file_types):
    return sorted(list(set([f for ext in file_types for f in glob.glob(f"*.{ext}")])))  # 🗃️ Deduped treasure hunt!

# 🖼️ Snap those pics like a paparazzi—upload images with flair!
def upload_images(files, history, selected_files):
    if not files:
        return "No files uploaded", history, selected_files  # 😢 No pics, no party!
    uploaded = []
    for file in files:
        ext = file.name.split('.')[-1].lower()  # 🕵️ Sniffing out the file type!
        if ext in ["jpg", "png"]:
            output_path = f"img_{int(time.time())}_{os.path.basename(file.name)}"  # 🏷️ Tagging it fresh!
            with open(output_path, "wb") as f:
                f.write(file.read())  # 📸 Snap saved!
            uploaded.append(output_path)
            history.append(f"Uploaded Image: {output_path}")  # 📜 Logging the fame!
            selected_files[output_path] = False  # ✅ Unchecked for now!
    return f"Uploaded {len(uploaded)} images", history, selected_files

# 📜 Scribble some docs—PDFs and more, oh what a bore!
def upload_documents(files, history, selected_files):
    if not files:
        return "No files uploaded", history, selected_files  # 📝 No docs, no drama!
    uploaded = []
    for file in files:
        ext = file.name.split('.')[-1].lower()  # 🕵️ Peeking at the paper type!
        if ext in ["pdf"]:  # Limiting to PDF for demo simplicity
            output_path = f"doc_{int(time.time())}_{os.path.basename(file.name)}"  # 🏷️ Stamping the scroll!
            with open(output_path, "wb") as f:
                f.write(file.read())  # 📜 Scroll secured!
            uploaded.append(output_path)
            history.append(f"Uploaded Document: {output_path}")  # 📜 Noted in history!
            selected_files[output_path] = False  # ✅ Still on the bench!
    return f"Uploaded {len(uploaded)} documents", history, selected_files

# 📊 Data nerd alert—CSV uploads for the win!
def upload_datasets(files, history, selected_files):
    if not files:
        return "No files uploaded", history, selected_files  # 📈 No data, no geek-out!
    uploaded = []
    for file in files:
        ext = file.name.split('.')[-1].lower()  # 🕵️ Cracking the data code!
        if ext == "csv":
            output_path = f"data_{int(time.time())}_{os.path.basename(file.name)}"  # 🏷️ Labeling the stats!
            with open(output_path, "wb") as f:
                f.write(file.read())  # 📊 Stats stashed!
            uploaded.append(output_path)
            history.append(f"Uploaded Dataset: {output_path}")  # 📜 Data’s in the books!
            selected_files[output_path] = False  # ✅ Not picked yet!
    return f"Uploaded {len(uploaded)} datasets", history, selected_files

# 🖼️ Gallery glow-up—show off all your files in style!
def update_galleries(history, selected_files):
    galleries = {
        "images": get_gallery_files(["jpg", "png"]),  # 🖼️ Picture parade!
        "documents": get_gallery_files(["pdf"]),  # 📜 Doc depot!
        "datasets": get_gallery_files(["csv"]),  # 📊 Data den!
    }
    gallery_outputs = {
        "images": [(Image.open(f), os.path.basename(f)) for f in galleries["images"]],  # 🖼️ Picture perfect!
        "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"]],  # 📜 Doc dazzle!
        "datasets": [(f, os.path.basename(f)) for f in galleries["datasets"]],  # 📊 Data delight!
    }
    history.append(f"Updated galleries: {sum(len(g) for g in galleries.values())} files")  # 📜 Gallery grand total!
    return gallery_outputs, history, selected_files

# 📂 Sidebar swagger—download links that scream “take me home!”
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]  # 📥 Download goodies!
    return file_list, history

# ✅ Check it or wreck it—toggle those selections like a pro!
def toggle_selection(file_list, selected_files):
    for file in file_list:
        selected_files[file] = not selected_files.get(file, False)  # ✅ Flip the switch, baby!
    return selected_files

# 📊 Dataframe demo—showing off Gradio 5.21.0+ dataframe mastery!
def get_dataframe():
    df = pd.DataFrame({
        "Name": ["Alice", "Bob", "Charlie"],
        "Age": [25, 30, 35],
        "Score": [95.5, 87.0, 92.3]
    })
    return df

# 📜 Mermaid.js demo—flowchart fun from 5.23.0!
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]
"""

🎨 Code editor demo—Jedi completion from 5.23.0!
def get_code_snippet():
return "def hello(name):\n    return f'Hello, {name}!'"

🎪 Gradio UI—step right up to the AI circus!
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}")  # 🎉 Welcome to the big top with version check!
history = gr.State(value=[])  # 📜 The ringmaster’s logbook!
selected_files = gr.State(value={})  # ✅ The chosen ones, ready to perform!

with gr.Row():
with gr.Column(scale=1):
gr.Markdown("## 📁 Files")  # 🗃️ The file circus tent!
sidebar_files = gr.Files(label="Downloads", height=300)  # 📥 Grab your souvenirs here!

with gr.Column(scale=3):
with gr.Row():
gr.Markdown("## 🛠️ Toolbar")  # 🔧 The circus control panel!
select_btn = gr.Button("✅ Select")  # ✅ Pick your performers!

with gr.Tabs():
with gr.TabItem("📤 Upload"):  # 📤 The upload trapeze!
with gr.Row():
img_upload = gr.File(label="🖼️ Images (jpg/png)", file_count="multiple")  # 🖼️ Picture trapeze!
doc_upload = gr.File(label="📜 Docs (pdf)", file_count="multiple")  # 📜 Doc drop!
with gr.Row():
data_upload = gr.File(label="📊 Data (csv)", file_count="multiple")  # 📊 Data dive!
upload_status = gr.Textbox(label="Status")  # 📢 Ringmaster’s update!
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"):  # 🖼️ The big top showcase!
img_gallery = gr.Gallery(label="🖼️ Images (jpg/png)", columns=4, height="auto")  # 🖼️ Picture parade!
doc_gallery = gr.Gallery(label="📜 Docs (pdf)", columns=4, height="auto")  # 📜 Doc depot!
data_gallery = gr.Gallery(label="📊 Data (csv)", columns=4, height="auto")  # 📊 Data den!
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"):  # 🔍 The magic trick tent!
gr.Markdown("### 📊 Dataframe Mastery (5.21.0)")  # 📊 Flexing new dataframe tricks!
df_output = gr.Dataframe(value=get_dataframe, interactive=True, static_columns=["Name"], wrap=True)  # 🔥 Static columns, drag selection from 5.21.0!
gr.Markdown("### 📜 Mermaid.js Flowchart (5.23.0)")  # 📜 Mermaid.js from 5.23.0!
mermaid_output = gr.Markdown(value=get_mermaid_chart)  # 🌐 Flowchart fun!
gr.Markdown("### 🎨 Code Editor with Jedi Completion (5.23.0)")  # 🎨 Jedi power from 5.23.0!
code_output = gr.Code(value=get_code_snippet, language="python", interactive=True)  # ✍️ Code with autocompletion!
gr.Markdown("### 💥 Deep Link Button (5.23.0)")  # 💥 Deep links from 5.23.0!
DeepLinkButton(label="Link to Latest Output", variant="secondary", deep_link="/gallery/images")  # 🔥 Secondary variant from 5.23.0!

with gr.TabItem("📜 History"):  # 📜 The logbook showcase!
history_output = gr.Textbox(label="History", lines=5, value="\n".join(history.value), interactive=False)  # 📜 What’s been cooking?

🎉 Auto-update history on load—Gradio 5.20.1 event listener vibes!
demo.load(lambda h: "\n".join(h[-5:]), inputs=[history], outputs=[history_output])

🎉 Launch the circus—step right up, folks!
demo.launch()