From 03f71476c8a3bf70699afcab174a18e90bb81889 Mon Sep 17 00:00:00 2001 From: "BIJAN_G16\\bijan" Date: Fri, 23 May 2025 14:22:25 +0200 Subject: [PATCH] Added Visualiztion code --- project/.gitignore | 3 +- project/__pycache__/config.cpython-310.pyc | Bin 1158 -> 1222 bytes project/config.py | 10 +- project/main.py | 27 +++++- .../__pycache__/block_black.cpython-310.pyc | Bin 1024 -> 1024 bytes .../__pycache__/block_random.cpython-310.pyc | Bin 1012 -> 1003 bytes .../__pycache__/block_white.cpython-310.pyc | Bin 1019 -> 1019 bytes project/obfuscation/block_random.py | 2 +- .../__pycache__/visualizer.cpython-310.pyc | Bin 0 -> 3354 bytes project/visualization/visualizer.py | 89 ++++++++++++++++++ 10 files changed, 124 insertions(+), 7 deletions(-) create mode 100644 project/visualization/__pycache__/visualizer.cpython-310.pyc create mode 100644 project/visualization/visualizer.py diff --git a/project/.gitignore b/project/.gitignore index 915368f..d8b2980 100644 --- a/project/.gitignore +++ b/project/.gitignore @@ -1,2 +1,3 @@ datasets/* -evaluation_results/* \ No newline at end of file +evaluation_results/* +visual_results/* \ No newline at end of file diff --git a/project/__pycache__/config.cpython-310.pyc b/project/__pycache__/config.cpython-310.pyc index db698c942de9311dfe4a023fba6abdca40eaef05..8f9e061750de16d7e9968a4f3c1a3bf1195e6ae0 100644 GIT binary patch delta 227 zcmZqUJjThJ&&$ij00h?I1{o(N@}A^k19BXIxHw_r0|Qg8D4rB8w#ADZIf9ntYS(8Jk6`_{%bjOA~YAi&BeAb4rT!L)>3IGVA~V delta 164 zcmX@c*~ZD6&&$ij00dLC^)n17@}A^k1#%pKxHxL!0|R}|6bR&+!xF`l!X3q%%Gb=0 z$`8Z>Kr9HvLd^{6tWm-#Ji!c_ypvrSo0&s2Stj3QG+}Y`(-fI3&vbpV0COyxIMB!< q@yW%^K8!k(4={`IG64Z22(tZU;h6lKd946M30NJ7keIxLMF{|+!y^s= diff --git a/project/config.py b/project/config.py index a6e9b9d..eb81aa0 100644 --- a/project/config.py +++ b/project/config.py @@ -16,13 +16,15 @@ class Config: face_model_type="yunet" evaluation_results_directory = "evaluation_results/" + visual_results_directory = "visual_results/" verbose=True - tasks = {"preprocessing": True, # optional if already done - "obfuscation": True, # optional if already done - "post_extract": True, # optional if already done - "analysis": True # optional if already done + tasks = {"preprocessing": False, # optional if already done + "obfuscation": False, # optional if already done + "post_extract": False, # optional if already done + "analysis": False, # optional if already done + "visualize": True #Should be always true, since it is the last step for reasoning } diff --git a/project/main.py b/project/main.py index 4f71686..fb2d639 100644 --- a/project/main.py +++ b/project/main.py @@ -1,11 +1,14 @@ import json import os +from pathlib import Path + from config import Config from data_loader import DatasetLoader from image_preprocessor import DataPreprocessor from meta_data.comparator import Comparator from meta_data.post_extraction import PostExtractor from obfuscation.obfuscation_engine import ObfuscationEngine +from visualization.visualizer import Visualizer ##Motivation @@ -76,7 +79,29 @@ def main(): print(f"Saving results in {current_technique_results_directory}") with open(current_technique_results_directory, "w") as f: json.dump(technique_result_dict, f, indent=4) - #TODO: 5. Visualize results + + if Config.tasks["visualize"]: + print("5. Running visualization") + out_dir = Path(Config.visual_results_directory); out_dir.mkdir(exist_ok=True) + viz = Visualizer(Config.evaluation_results_directory) + for ds in viz.datasets(): + for cat in viz.categories(): + if cat == "meta": + continue + fname = f"{ds}_{cat}.png" + save_path = out_dir / fname + viz.plot_category_by_tech(dataset=ds, + category=cat, + save=save_path) + print(f"📊 {save_path} gespeichert") + +#TODO: metriken aus grafik rausnehmen; für jeden 3 +#TODO: ohne UTK + +#TODO Bestes gesicht? FaceBox iou + + + if __name__ == '__main__': diff --git a/project/obfuscation/__pycache__/block_black.cpython-310.pyc b/project/obfuscation/__pycache__/block_black.cpython-310.pyc index 2e3562d7cd6f63dec9d52837e39b17f4aae370b4..053a167b54aec85c6d5862a0bd1d86522012da21 100644 GIT binary patch delta 20 acmZqRXyD+^=jG*M0D=iR`Wv~wG6Mi7@dQo) delta 20 acmZqRXyD+^=jG*M0D@`9WH)kuWd;B%T?E_! diff --git a/project/obfuscation/__pycache__/block_random.cpython-310.pyc b/project/obfuscation/__pycache__/block_random.cpython-310.pyc index 5e499224c4c3aaac86b612cd5de3c1840c8fbb5f..37610788ebddc8f39be811f94fb1885bea080cda 100644 GIT binary patch delta 33 mcmeyu{+gXPpO=@50SNj-4KfyQu0Ro$h(P&FN&uqF)t-QH$EvRKRJ8z5his;00lk`0ssI2 diff --git a/project/obfuscation/__pycache__/block_white.cpython-310.pyc b/project/obfuscation/__pycache__/block_white.cpython-310.pyc index 5e83a9f7ce70a56218bc39274f6fd02de29ab21b..35bfc713d682827c4e04b126f21e99be394915a0 100644 GIT binary patch delta 19 Zcmey({+pdEpO=@50SIR6Y~=dL3;;Fl1sDJT delta 19 Zcmey({+pdEpO=@50SIcfH*$Ss1^_iQ1o;2} diff --git a/project/obfuscation/block_random.py b/project/obfuscation/block_random.py index d5daddb..4ec44b1 100644 --- a/project/obfuscation/block_random.py +++ b/project/obfuscation/block_random.py @@ -17,4 +17,4 @@ class Randoming(ObfuscationTechnique): return obf def name(self): - return "random_block" \ No newline at end of file + return "random" \ No newline at end of file diff --git a/project/visualization/__pycache__/visualizer.cpython-310.pyc b/project/visualization/__pycache__/visualizer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..147239f85f3680a4e3fe23b49240a027eef5e143 GIT binary patch literal 3354 zcmZ`+OOG4J5uWaOa5&3->S3*9%i}}{L~FGO5FiIfwv^~$#7byIavq>o8O*Yq+~E#q zW_x-BEj0uTuX5BWK!DgWKpMH|lv|KPZu%AJLk`MmkxLNY76z269&&eOJ56*?byq*C ztE;{$rt|Zj0p%~9?{6K<8^*t|bG(?)xn>w7Zvnv!Mq*&R~rl!r38V7|hP;Rw4 z$UI&w=v+flHh|zpn=qqI8EKo`8rzIcNZVoOn9ZCg799OLt1}NM7pOVb0IJU3V2f-C zD6hU;Ut#Cjo9r}u?THQI_-vJ(1x|ylfM9Pa?^jV?gmE z3(dXDJE>rPCQ|?6bj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z5AhvbJ>BUx(({YnMDv_?tetAz`CPP2g$bqmOk zKq7&$Sk*E}C*x?dN&&ktB<|w4lZ6QjbMYJOEQ7_MN5VWv$ut@{)mL1>6)3>BNv7N@ V)&1W?@XS%-hS5N;hc{ZG{{tAffJXoT literal 0 HcmV?d00001 diff --git a/project/visualization/visualizer.py b/project/visualization/visualizer.py new file mode 100644 index 0000000..f4e836e --- /dev/null +++ b/project/visualization/visualizer.py @@ -0,0 +1,89 @@ +from __future__ import annotations +from pathlib import Path +import re, json +import pandas as pd +import matplotlib.pyplot as plt + +class Visualizer: + """ + Liest results_{dataset}_{technique}.json und hält ein langes DataFrame. + • ein Record pro (dataset, technique, category, metric) + • keine Aggregation nötig – jede Datei enthält EINEN Wert je Metrik + """ + + _PTN = re.compile(r"results_(?P[^_]+)_(?P[^.]+)\.json$") + + def __init__(self, json_dir: str | Path): + self.json_dir = Path(json_dir) + if not self.json_dir.exists(): + raise FileNotFoundError(self.json_dir) + self.df = self._load_jsons() + + # ------------------------------------------------------------------ + # Public helpers + # ------------------------------------------------------------------ + def datasets(self) -> list[str]: + return sorted(self.df["dataset"].unique()) + + def categories(self) -> list[str]: + return sorted(self.df["category"].unique()) + + def metrics_of(self, category: str) -> list[str]: + return sorted(self.df[self.df["category"] == category]["metric"].unique()) + + # -- Kernplot ------------------------------------------------------- + def plot_category_by_tech(self, + dataset: str, + category: str, + figsize=(9, 5), + save: str | Path | None = None): + """ + Ein Balkendiagramm: alle Metriken dieser Kategorie, + gruppiert nach Technik, nur für EIN Dataset. + """ + sub = self.df[(self.df["dataset"] == dataset) & + (self.df["category"] == category)] + if sub.empty: + print(f"[⚠] Kein Eintrag für Dataset={dataset}, Cat={category}") + return + + # Pivot: index = technique, columns = metrics + pivot = sub.pivot(index="technique", columns="metric", values="value") + print(pivot) + fig, ax = plt.subplots(figsize=figsize) + pivot.plot(kind="bar", ax=ax) + + ax.set_title(f"{dataset} – {category.capitalize()} metrics") + ax.set_xlabel("Technique") + ax.set_ylabel("score") + ax.grid(axis="y", linestyle="--", alpha=0.4) + ax.legend(title="metric", bbox_to_anchor=(1.02, 1), loc="upper left") + + plt.tight_layout() + if save: + fig.savefig(save, dpi=150, bbox_inches="tight") + plt.close(fig) + return fig, ax + + # ------------------------------------------------------------------ + # intern + # ------------------------------------------------------------------ + def _load_jsons(self) -> pd.DataFrame: + recs = [] + for file in self.json_dir.glob("results_*_*.json"): + m = self._PTN.match(file.name) + if not m: + continue + dataset, tech = m.group("dataset"), m.group("technique") + data = json.load(open(file, "r")) + + for cat, metrics in data.items(): + for metric, val in metrics.items(): + recs.append({"dataset": dataset, + "technique": tech, + "category": cat, + "metric": metric, + "value": val}) + if not recs: + raise RuntimeError("Keine passenden JSON-Dateien gefunden.") + return pd.DataFrame.from_records(recs)