diff --git a/tab_gallery_sorter.py b/tab_gallery_sorter.py index a10c166..f288d69 100644 --- a/tab_gallery_sorter.py +++ b/tab_gallery_sorter.py @@ -4,11 +4,11 @@ import math from engine import SorterEngine # ========================================== -# 1. HELPER CALLBACKS (Prevent Refreshing) +# 1. GLOBAL CALLBACKS (Prevents Page Refresh) # ========================================== + def cb_tag_image(img_path, selected_cat): - """Tags an image without reloading the whole page.""" - # Safety check: Don't tag if a separator (--- A ---) is selected + """Tags an image. Updates DB immediately.""" if selected_cat.startswith("---") or selected_cat == "": st.toast("⚠️ Select a valid category first!", icon="🚫") return @@ -16,7 +16,7 @@ def cb_tag_image(img_path, selected_cat): staged = SorterEngine.get_staged_data() ext = os.path.splitext(img_path)[1] - # Auto-increment filename logic + # Auto-increment logic count = len([v for v in staged.values() if v['cat'] == selected_cat]) + 1 new_name = f"{selected_cat}_{count:03d}{ext}" @@ -27,19 +27,25 @@ def cb_untag_image(img_path): SorterEngine.clear_staged_item(img_path) def cb_delete_image(img_path): - """Moves image to trash immediately.""" + """Moves image to trash.""" SorterEngine.delete_to_trash(img_path) def cb_apply_batch(current_batch, path_o, cleanup_mode): - """Commits the batch to disk.""" + """Commits files to disk.""" SorterEngine.commit_batch(current_batch, path_o, cleanup_mode) def cb_change_page(delta): - """Updates the page number before the script runs.""" + """Updates page number (-1 or +1).""" if 't5_page' not in st.session_state: st.session_state.t5_page = 0 st.session_state.t5_page += delta +def cb_jump_page(k): + """Updates page number from direct input box.""" + val = st.session_state[k] + st.session_state.t5_page = val - 1 + + # ========================================== # 2. FRAGMENT: SIDEBAR (Category Manager) # ========================================== @@ -48,10 +54,8 @@ def render_sidebar_content(): st.divider() st.subheader("🏷️ Category Manager") - # --- GET CATEGORIES & FORMAT LIST --- + # --- PREPARE LIST (With Separators) --- cats = SorterEngine.get_categories() - - # Insert visual separators (e.g. "--- A ---") processed_cats = [] last_char = "" if cats: @@ -62,21 +66,18 @@ def render_sidebar_content(): processed_cats.append(cat) last_char = current_char - # --- STATE MANAGEMENT --- - # Default selection if none exists + # --- STATE SYNC --- if "t5_active_cat" not in st.session_state: st.session_state.t5_active_cat = cats[0] if cats else "Default" - - # Handle case where selected category was deleted - # We strip separators to check validity against raw 'cats' list + + # Fallback if selection was deleted current_selection = st.session_state.t5_active_cat if not current_selection.startswith("---") and current_selection not in cats: st.session_state.t5_active_cat = cats[0] if cats else "Default" # --- RADIO SELECTION --- selection = st.radio("Active Tag", processed_cats, key="t5_radio_select") - - # Update global state (Ignore separators) + if not selection.startswith("---"): st.session_state.t5_active_cat = selection @@ -85,7 +86,6 @@ def render_sidebar_content(): # --- TABS: ADD / EDIT --- tab_add, tab_edit = st.tabs(["➕ Add", "✏️ Edit"]) - # ADD NEW with tab_add: c1, c2 = st.columns([3, 1]) new_cat = c1.text_input("New Name", label_visibility="collapsed", placeholder="New...", key="t5_new_cat") @@ -94,7 +94,6 @@ def render_sidebar_content(): SorterEngine.add_category(new_cat) st.rerun() - # EDIT / DELETE with tab_edit: target_cat = st.session_state.t5_active_cat is_valid = target_cat and not target_cat.startswith("---") and target_cat in cats @@ -102,9 +101,8 @@ def render_sidebar_content(): if is_valid: st.caption(f"Editing: **{target_cat}**") - # RENAME: Key includes target_cat so input resets when selection changes + # RENAME rename_val = st.text_input("Rename to:", value=target_cat, key=f"ren_{target_cat}") - if st.button("💾 Save Name", key=f"save_{target_cat}", use_container_width=True): if rename_val and rename_val != target_cat: SorterEngine.rename_category(target_cat, rename_val) @@ -116,7 +114,7 @@ def render_sidebar_content(): # DELETE if st.button("🗑️ Delete Category", key=f"del_cat_{target_cat}", type="primary", use_container_width=True): SorterEngine.delete_category(target_cat) - st.rerun() # Refresh sidebar to remove deleted item + st.rerun() else: st.info("Select a valid category to edit.") @@ -126,13 +124,8 @@ def render_sidebar_content(): # ========================================== @st.fragment def render_gallery_grid(current_batch, quality, grid_cols): - """ - Renders images. Updates locally using callbacks without full page reload. - """ staged = SorterEngine.get_staged_data() selected_cat = st.session_state.get("t5_active_cat", "Default") - - # Disable tagging if user selected a separator tagging_disabled = selected_cat.startswith("---") cols = st.columns(grid_cols) @@ -144,15 +137,15 @@ def render_gallery_grid(current_batch, quality, grid_cols): is_staged = img_path in staged with st.container(border=True): - # Header: Name & Delete + # Header c_head1, c_head2 = st.columns([5, 1]) c_head1.caption(os.path.basename(img_path)[:15]) - # DELETE BUTTON + # DELETE (Callback) c_head2.button("❌", key=f"del_{unique_key}", on_click=cb_delete_image, args=(img_path,)) - # STATUS BANNER + # STATUS if is_staged: st.success(f"🏷️ {staged[img_path]['cat']}") @@ -161,7 +154,7 @@ def render_gallery_grid(current_batch, quality, grid_cols): if img_data: st.image(img_data, use_container_width=True) - # ACTION BUTTONS + # ACTIONS (Callbacks) if not is_staged: st.button("Tag", key=f"tag_{unique_key}", disabled=tagging_disabled, @@ -174,42 +167,33 @@ def render_gallery_grid(current_batch, quality, grid_cols): # ========================================== -# 4. FRAGMENT: BATCH ACTIONS (Apply) +# 4. FRAGMENT: BATCH ACTIONS # ========================================== @st.fragment def render_batch_actions(current_batch, path_o, page_num): - """ - Isolates the 'Apply' section so radio buttons don't reload the page. - """ st.write(f"### 🚀 Batch Actions (Page {page_num})") c_act1, c_act2 = st.columns([3, 1]) - - # Radio button changes stay local to this fragment cleanup = c_act1.radio("Untagged Action:", ["Keep", "Move to Unused", "Delete"], horizontal=True, key="t5_cleanup_mode") - # The Apply button triggers disk operations - # We allow this to rerun the fragment, but users might need to navigate - # to refresh the main list if files disappear. if c_act2.button("APPLY PAGE", type="primary", use_container_width=True): with st.spinner("Processing..."): SorterEngine.commit_batch(current_batch, path_o, cleanup) st.success("Batch processed!") - # Rerun to clear the processed images from the view st.rerun() # ========================================== -# 5. MAIN RENDER ENTRY POINT +# 5. MAIN RENDERER # ========================================== def render(quality, profile_name): st.subheader("🖼️ Gallery Staging Sorter") - # Init Page State + # Init State if 't5_page' not in st.session_state: st.session_state.t5_page = 0 - # Load Settings + # Load Paths profiles = SorterEngine.load_profiles() p_data = profiles.get(profile_name, {}) @@ -224,7 +208,7 @@ def render(quality, profile_name): if not os.path.exists(path_s): return - # --- RENDER SIDEBAR (FRAGMENT) --- + # --- RENDER SIDEBAR --- with st.sidebar: render_sidebar_content() @@ -234,7 +218,7 @@ def render(quality, profile_name): page_size = c_v1.slider("Images per Page", 12, 100, 24, 4) grid_cols = c_v2.slider("Grid Columns", 2, 8, 4) - # --- LOAD DATA & PAGINATE --- + # --- DATA & MATH --- all_images = SorterEngine.get_images(path_s, recursive=True) if not all_images: st.info("No images found.") @@ -242,42 +226,49 @@ def render(quality, profile_name): total_items = len(all_images) total_pages = math.ceil(total_items / page_size) - if st.session_state.t5_page >= total_pages: - st.session_state.t5_page = max(0, total_pages - 1) - if st.session_state.t5_page < 0: - st.session_state.t5_page = 0 + + # Safety Bounds Check + if st.session_state.t5_page >= total_pages: st.session_state.t5_page = max(0, total_pages - 1) + if st.session_state.t5_page < 0: st.session_state.t5_page = 0 start_idx = st.session_state.t5_page * page_size end_idx = start_idx + page_size current_batch = all_images[start_idx:end_idx] - # --- NAVIGATION CONTROLS (Optimized) --- - def nav_controls(key): - c1, c2, c3 = st.columns([1, 2, 1]) + # --- NAVIGATION BAR COMPONENT --- + def nav_controls(key_suffix): + # Layout: [Prev] [Number Input] [Next] + c1, c2, c3 = st.columns([1, 2, 1], vertical_alignment="center") - # Previous Button - # We pass -1 to the callback to subtract a page c1.button("⬅️ Prev", disabled=(st.session_state.t5_page == 0), on_click=cb_change_page, args=(-1,), - key=f"p_{key}") + key=f"p_{key_suffix}", use_container_width=True) - # Page Indicator - c2.markdown(f"
Page {st.session_state.t5_page + 1} / {total_pages}
", unsafe_allow_html=True) + c2.number_input( + "Go to Page", + min_value=1, max_value=total_pages, + value=st.session_state.t5_page + 1, + step=1, + label_visibility="collapsed", + key=f"jump_{key_suffix}", + on_change=cb_jump_page, args=(f"jump_{key_suffix}",) + ) - # Next Button - # We pass 1 to the callback to add a page c3.button("Next ➡️", disabled=(st.session_state.t5_page >= total_pages - 1), on_click=cb_change_page, args=(1,), - key=f"n_{key}") - - # --- RENDER GALLERY (FRAGMENT) --- - render_gallery_grid(current_batch, quality, grid_cols) + key=f"n_{key_suffix}", use_container_width=True) + # --- RENDER PAGE --- st.divider() - nav_controls("bottom") + nav_controls("top") # Top Nav + + render_gallery_grid(current_batch, quality, grid_cols) # Grid + + st.divider() + nav_controls("bottom") # Bottom Nav st.divider() - # --- RENDER BATCH ACTIONS (FRAGMENT) --- + # Batch Actions render_batch_actions(current_batch, path_o, st.session_state.t5_page + 1) \ No newline at end of file