awacke1's picture
Update app.py
7d67450 verified
raw
history blame
10.9 kB
# 😂 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()