22import subprocess
33from carbontracker .tracker import CarbonTracker
44from carbontracker import parser
5+ from carbontracker .report import generate_report_from_log
56import ast
7+ import os
68
79
810def parse_logs (log_dir ):
911 parser .print_aggregate (log_dir = log_dir )
1012
1113
14+ def generate_report (log_file , output_pdf ):
15+ """Generate a PDF report from a log file"""
16+ if not os .path .exists (log_file ):
17+ print (f"Error: Log file { log_file } does not exist" )
18+ return
19+ generate_report_from_log (log_file , output_pdf )
20+ print (f"Report generated: { output_pdf } " )
21+
22+
1223def main ():
1324 """
1425 The **carbontracker** CLI allows the user to track the energy consumption and carbon intensity of any program.
@@ -18,6 +29,8 @@ def main():
1829 --log_dir (path, optional): Log directory. Defaults to `./logs`.
1930 --api_keys (str, optional): API keys in a dictionary-like format, e.g. `\' {"electricitymaps": "YOUR_KEY"}\' `
2031 --parse (path, optional): Directory containing the log files to parse.
32+ --report (path, optional): Generate a PDF report from a log file.
33+ --output (path, optional): Output path for the generated report. Defaults to 'carbon_report.pdf'
2134
2235 Example:
2336 Tracking the carbon intensity of `script.py`.
@@ -31,6 +44,10 @@ def main():
3144 Parsing logs:
3245
3346 $ carbontracker --parse ./internal_logs
47+
48+ Generating a report:
49+
50+ $ carbontracker --report ./logs/carbontracker.log --output report.pdf
3451 """
3552
3653 # Create a parser for the known arguments
@@ -44,6 +61,9 @@ def main():
4461 default = None ,
4562 )
4663 cli_parser .add_argument ("--parse" , type = str , help = "Directory containing the log files to parse." )
64+ cli_parser .add_argument ("--report" , type = str , help = "Generate a PDF report from a log file." )
65+ cli_parser .add_argument ("--output" , type = str , default = "carbon_report.pdf" ,
66+ help = "Output path for the generated report." )
4767
4868 # Parse known arguments only
4969 known_args , remaining_args = cli_parser .parse_known_args ()
@@ -53,6 +73,11 @@ def main():
5373 parse_logs (known_args .parse )
5474 return
5575
76+ # Check if the --report argument is provided
77+ if known_args .report :
78+ generate_report (known_args .report , known_args .output )
79+ return
80+
5681 # Parse the API keys string into a dictionary
5782 api_keys = ast .literal_eval (known_args .api_keys ) if known_args .api_keys else None
5883
0 commit comments