Skip to content

Commit

Permalink
move metadata creation to reporter
Browse files Browse the repository at this point in the history
  • Loading branch information
pixelsoup42 committed Oct 13, 2023
1 parent f09dd28 commit 4dbe806
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
4 changes: 1 addition & 3 deletions src/cardano_account_pandas_dumper/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
# Error codes due to project key rate limiting or capping
PROJECT_KEY_ERROR_CODES = frozenset([402, 403, 418, 429])

CREATOR_STRING="https://github.com/pixelsoup42/cardano_account_pandas_dumper"

def _create_arg_parser():
result = argparse.ArgumentParser(
Expand Down Expand Up @@ -232,8 +231,7 @@ def main():
if args.graph_output:
reporter.plot_balance()
try:
plt.savefig(args.graph_output,
metadata={"Creator":CREATOR_STRING,"Software":CREATOR_STRING})
plt.savefig(args.graph_output,metadata=reporter.get_graph_metadata(args.graph_output),pad_inches=0.5)
except OSError as exception:
warnings.warn(f"Failed to write graph file: {exception}")
print("Done.")
Expand Down
29 changes: 27 additions & 2 deletions src/cardano_account_pandas_dumper/cardano_account_pandas_dumper.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
Dict,
FrozenSet,
List,
Mapping,
MutableMapping,
Optional,
Set,
Expand All @@ -31,6 +32,9 @@
import pandas as pd
from blockfrost import BlockFrostApi

CREATOR_STRING="https://github.com/pixelsoup42/cardano_account_pandas_dumper"



class AccountData:
"""Hold data retrieved from the API to allow checkpointing it."""
Expand Down Expand Up @@ -624,6 +628,7 @@ def _make_logos_vector(self):
)

class _ImageLegendHandler(HandlerBase):
# TODO: pass asset instead of data, move code above to here, move outside class
def __init__(self, color, data: Any) -> None:
self.image = mpl.image.imread(data) if data is not None else None
self.color=color
Expand Down Expand Up @@ -658,7 +663,11 @@ def create_artists(
else:
return [rectangle]

def _plot_title(self):
return f"Asset balances in wallet until block {self.data.to_block}."

def plot_balance(self):
""" Create a Matplotlib plot with the asset balance over time."""
balance = self.make_balance_frame(with_total=False, raw_values=True).cumsum()
balance.sort_index(
axis=1,
Expand All @@ -675,20 +684,23 @@ def plot_balance(self):
plot=balance.plot(
ax=plot_ax,
logy=True,
title=f"Asset balances in wallet until block {self.data.to_block}.",
title=self._plot_title(),
legend=False,
)
# Get font size
text=pyplot.text(x=0,y=0,s="M", font_properties=font_properties)
text_bbox=text.get_window_extent()
text.remove()

self._make_logos_vector()
legend_font_scale=2
legend_ax.axis("off")
for text in legend_ax.legend(
plot.get_lines(),
[self.asset_names.get(c, c) for c in balance.columns],
handler_map={
plot.get_lines()[i]: self._ImageLegendHandler(color=f"C{i}",data=self.logos[balance.columns[i]])
plot.get_lines()[i]:
self._ImageLegendHandler(color=f"C{i}",data=self.logos[balance.columns[i]])
for i in range(len(balance.columns))
},
labelcolor="linecolor",
Expand All @@ -700,3 +712,16 @@ def plot_balance(self):

).get_texts():
text.set(y=text.get_window_extent().y0 + legend_font_scale * text_bbox.height / 2)
pyplot.tight_layout()

def get_graph_metadata(self, filename:str) -> Mapping :
"""Return graph metadata depending on file extension."""
extension=os.path.splitext(filename)[1]
if extension in (".svg",".pdf"):
return { "Creator": CREATOR_STRING, "Title": self._plot_title() }
elif extension==".png":
return {"Software" : CREATOR_STRING,"Title": self._plot_title()}
elif extension in (".ps",".eps"):
return { "Creator": CREATOR_STRING }
else:
return {}

0 comments on commit 4dbe806

Please sign in to comment.