Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse files229 unmodified lines23023123223323323423523623723823924024124224324024124424524624724824925025125225325425556 unmodified lines3123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583 unmodified lines3623633643133653663673683693703183713723733743223753763773785 unmodified lines38438538633438738838939039139239339439539639739839940040140240340440540640740840941041141241341441541621 unmodified lines43843944044144244344444544644744836344945045145245345445537045645745845943 unmodified lines5035045054205065075085095105115125135145155164274284295175185195205215224325235245255261 unmodified line528529530440531532533534535536537538539540541443542543544229 unmodified lines result[item['type']] = item['full_path']
return result
def process_all(self, rules):
def process_all(self, rules, overrides=None):
# rules: dict of {type: rule_config}
# overrides: dict of {sample_id: {type: rule_config}}
if overrides is None:
overrides = {}
output_zip = tempfile.mktemp(suffix='.zip')
output_dir = tempfile.mkdtemp()
for item in self.file_map:
img_type = item['type']
# Default to None rule if not specified
rule = rules.get(img_type, {'action': 'None'})
sample_id = item['sample_id']
# Determine rule: Override > Type Rule > Default
rule = {'action': 'None'}
if sample_id in overrides and img_type in overrides[sample_id]:
rule = overrides[sample_id][img_type]
elif img_type in rules:
rule = rules[img_type]
try:
img = Image.open(item['full_path'])56 unmodified linesmatrix = ImageMatrix()
# Store rules globally for this session (Not multi-user safe, but fits current architecture)
global_rules = {}
# Store overrides: {sample_id: {type: rule}}
global_overrides = {}
def get_rules_summary():
lines = []
# Batch Rules
if global_rules:
lines.append("#### 📦 Batch Rules")
for t, r in global_rules.items():
p = r['params']
p_str = ""
if r['action'] == 'Resize':
p_str = f"{p.get('w')}x{p.get('h')}"
elif r['action'] == 'Auto Trim':
p_str = f"Thresh={p.get('threshold')}"
elif r['action'] == 'Manual Crop':
p_str = f"x={p.get('x')},y={p.get('y')},w={p.get('w')},h={p.get('h')}"
lines.append(f"* **{t}**: {r['action']} `[{p_str}]`")
# Overrides
if global_overrides:
lines.append("\n#### 🔧 Overrides")
for sid, types in global_overrides.items():
for t, r in types.items():
p = r['params']
p_str = ""
if r['action'] == 'Resize':
p_str = f"{p.get('w')}x{p.get('h')}"
elif r['action'] == 'Auto Trim':
p_str = f"Thresh={p.get('threshold')}"
elif r['action'] == 'Manual Crop':
p_str = f"x={p.get('x')},y={p.get('y')},w={p.get('w')},h={p.get('h')}"
lines.append(f"* **{sid}** ({t}): {r['action']} `[{p_str}]`")
if not lines:
return "No rules configured yet."
return "\n".join(lines)
def handle_upload(file, use_llm_chk):
if file is None:3 unmodified lines types = matrix.types
samples = matrix.samples
# Reset rules
# Reset rules and overrides
global_rules.clear()
global_overrides.clear()
summary_text = f"Found {len(samples)} samples and {len(types)} types.\nTypes: {', '.join(types)}"
return df, gr.update(choices=samples, value=samples[0] if samples else None), gr.update(choices=types, value=types[0] if types else None), summary_text
return df, gr.update(choices=samples, value=samples[0] if samples else None), gr.update(choices=types, value=types[0] if types else None), summary_text, get_rules_summary()
def save_rule(type_sel, action, p1, p2, p3, p4):
if not type_sel:
return "No type selected."
return "No type selected.", get_rules_summary()
params = {}
if action == 'Manual Crop':5 unmodified lines
rule = {'action': action, 'params': params}
global_rules[type_sel] = rule
return f"Saved rule for {type_sel}: {action}"
return f"Saved rule for Type: {type_sel} -> {action}", get_rules_summary()
def save_override(sample_id, type_sel, action, p1, p2, p3, p4):
if not sample_id or not type_sel:
return "Sample or Type not selected.", get_rules_summary()
params = {}
if action == 'Manual Crop':
params = {'x': p1, 'y': p2, 'w': p3, 'h': p4}
elif action == 'Resize':
params = {'w': p1, 'h': p2}
elif action == 'Auto Trim':
params = {'threshold': p1}
rule = {'action': action, 'params': params}
if sample_id not in global_overrides:
global_overrides[sample_id] = {}
global_overrides[sample_id][type_sel] = rule
return f"Saved OVERRIDE for {sample_id} / {type_sel} -> {action}", get_rules_summary()
def clear_override(sample_id, type_sel):
if sample_id in global_overrides and type_sel in global_overrides[sample_id]:
del global_overrides[sample_id][type_sel]
return f"Cleared override for {sample_id} / {type_sel}", get_rules_summary()
return "No override found to clear.", get_rules_summary()
def update_preview(sample_id, type_sel, action, p1, p2, p3, p4):
# p1-p4 are generic params mapped based on action21 unmodified lines path = images[type_sel]
orig_img = Image.open(path)
proc_img = apply_image_rule(orig_img.copy(), rule)
# Check if override exists
is_overridden = sample_id in global_overrides and type_sel in global_overrides[sample_id]
status_text = f"{type_sel} (Processed)"
if is_overridden:
status_text += " [OVERRIDE ACTIVE]"
results.append((orig_img, f"{type_sel} (Original)"))
results.append((proc_img, f"{type_sel} (Processed)"))
results.append((proc_img, status_text))
return results
def run_batch_process():
if not matrix.file_map:
return None
return matrix.process_all(global_rules)
return matrix.process_all(global_rules, global_overrides)
def generate_code_prompt(df_json, user_req):
# Fallback for complex needs43 unmodified lines
with gr.Row():
preview_btn = gr.Button("Preview Effect")
save_rule_btn = gr.Button("Save Rule for Type")
save_rule_btn = gr.Button("Save Rule for Type (Batch)")
with gr.Row():
save_override_btn = gr.Button("Save Override (This Sample Only)", variant="secondary")
clear_override_btn = gr.Button("Clear Override", variant="stop")
rule_status = gr.Markdown("")
with gr.Column():
preview_gallery = gr.Gallery(label="Preview", columns=2)
gr.Markdown("### 🚀 Batch Process")
process_btn = gr.Button("Apply Rules & Download", variant="primary")
download_output = gr.File(label="Download Result")
gr.Markdown("### 🚀 Batch Process")
rules_summary_display = gr.Markdown("No rules configured yet.")
process_btn = gr.Button("Apply Rules & Download", variant="primary")
download_output = gr.File(label="Download Result")
# Event Wiring
analyze_btn.click(handle_upload, inputs=[zip_input, use_llm_chk], outputs=[file_table, sample_selector, type_selector, structure_info])
analyze_btn.click(handle_upload, inputs=[zip_input, use_llm_chk], outputs=[file_table, sample_selector, type_selector, structure_info, rules_summary_display])
preview_btn.click(update_preview,
inputs=[sample_selector, type_selector, action_selector, p1, p2, p3, p4],1 unmodified line
save_rule_btn.click(save_rule,
inputs=[type_selector, action_selector, p1, p2, p3, p4],
outputs=[rule_status])
outputs=[rule_status, rules_summary_display])
save_override_btn.click(save_override,
inputs=[sample_selector, type_selector, action_selector, p1, p2, p3, p4],
outputs=[rule_status, rules_summary_display])
clear_override_btn.click(clear_override,
inputs=[sample_selector, type_selector],
outputs=[rule_status, rules_summary_display])
process_btn.click(run_batch_process, inputs=[], outputs=[download_output])
with gr.Accordion("💻 Code Gen Helper (Fallback)", open=False):
user_req = gr.Textbox(label="Describe your requirement")
gen_prompt_btn = gr.Button("Generate Prompt")apps/paper_image_tool.py+114-16