From cc7cbb798cbfd68aa899add87470cd5b06caaa9a Mon Sep 17 00:00:00 2001 From: Deuchnord Date: Sun, 19 Oct 2025 16:26:26 +0200 Subject: [PATCH] fix: revert "feat: remove PDF output" (#419) Fix #418 --- .gitignore | 4 ++ README.md | 5 ++ kosmorro/__main__.py | 32 +++++++---- kosmorro/assets/pdf/kosmorro.sty | 0 kosmorro/assets/pdf/template.tex | 0 kosmorro/dumper.py | 86 +++++++++++++++++++++++++++-- kosmorro/locales/messages.pot | 95 ++++++++++++++++++++------------ manpage/kosmorro.1.md | 10 +++- tests/general.py | 18 +++--- tests/output.py | 5 +- 10 files changed, 193 insertions(+), 62 deletions(-) create mode 100644 kosmorro/assets/pdf/kosmorro.sty create mode 100644 kosmorro/assets/pdf/template.tex diff --git a/.gitignore b/.gitignore index 06399ba..e89f60f 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,10 @@ kosmorro.egg-info .coverage coverage.xml +/kosmorrolib/assets/pdf/* +!/kosmorrolib/assets/pdf/*.tex +!/kosmorrolib/assets/pdf/*.sty + /manpage/* !/manpage/*.md diff --git a/README.md b/README.md index 094b5d0..feb23fe 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,11 @@ By default, it will give you the current Moon phase and, if any, the events that Kosmorro has a lot of available options to get exactly what you want, including the possibility to get planets rise and set. To get a list of them, run `kosmorro --help`, or read its manual with `man kosmorro`. You can also find usage examples in [the `tldr` manual](https://tldr.sh) with [`tldr kosmorro`](https://tldr.inbrowser.app/pages/common/kosmorro). +### Exporting to PDF + +Kosmorro can export the computation results to PDF files, but this feature requires first that you install some additional dependencies. +You can find documentation about this on [Kosmorro's website](https://kosmorro.space/cli/generate-pdf/). + ## Help translating Kosmorro! Kosmorro is translated on [Weblate](https://hosted.weblate.org/engage/kosmorro/), a popular free platform for crowd-sourced internationalization. diff --git a/kosmorro/__main__.py b/kosmorro/__main__.py index 13c8eb0..5155cd5 100644 --- a/kosmorro/__main__.py +++ b/kosmorro/__main__.py @@ -83,16 +83,23 @@ def run(): if output_format is None: output_format = "txt" - if output_format == "tex" and position is None: - print_stderr( - colored( - _( - "Output file will not contain the ephemerides, because you didn't provide the observation " - "coordinates." - ), - "yellow", + if output_format == "pdf": + print( + _( + "Save the planet and paper!\n" + "Consider printing your PDF document only if really necessary, and use the other side of the sheet." ) ) + if position is None: + print_stderr( + colored( + _( + "PDF output will not contain the ephemerides, because you didn't provide the observation " + "coordinates." + ), + "yellow", + ) + ) timezone = 0 @@ -233,11 +240,15 @@ def get_dumpers() -> {str: dumper.Dumper}: return { "txt": dumper.TextDumper, "json": dumper.JsonDumper, + "pdf": dumper.PdfDumper, "tex": dumper.LatexDumper, } def get_opening_mode(format: str) -> str: + if format == "pdf": + return "wb" + return "w" @@ -335,7 +346,8 @@ def get_args(output_formats: [str]): type=str, default=None, help=_( - "A file to export the output to. If not given, the standard output is used." + "A file to export the output to. If not given, the standard output is used. " + "This argument is needed for PDF format." ), ) parser.add_argument( @@ -343,7 +355,7 @@ def get_args(output_formats: [str]): dest="show_graph", action="store_false", help=_( - "Do not generate a graph to represent the rise and set times in the LaTeX file." + "Do not generate a graph to represent the rise and set times in the LaTeX or PDF file." ), ) parser.add_argument( diff --git a/kosmorro/assets/pdf/kosmorro.sty b/kosmorro/assets/pdf/kosmorro.sty new file mode 100644 index 0000000..e69de29 diff --git a/kosmorro/assets/pdf/template.tex b/kosmorro/assets/pdf/template.tex new file mode 100644 index 0000000..e69de29 diff --git a/kosmorro/dumper.py b/kosmorro/dumper.py index 7ee39a3..0496a05 100644 --- a/kosmorro/dumper.py +++ b/kosmorro/dumper.py @@ -43,9 +43,9 @@ from .utils import KOSMORRO_VERSION class Dumper(ABC): - ephemerides: [AsterEphemerides] + ephemerides: list[AsterEphemerides] moon_phase: MoonPhase - events: [Event] + events: list[Event] date: datetime.date timezone: int with_colors: bool @@ -53,9 +53,9 @@ class Dumper(ABC): def __init__( self, - ephemerides: [AsterEphemerides], + ephemerides: list[AsterEphemerides], moon_phase: MoonPhase, - events: [Event], + events: list[Event], date: datetime.date, timezone: int, with_colors: bool, @@ -281,7 +281,7 @@ class LatexDumper(Dumper): document = template - if self.ephemerides is None: + if len(self.ephemerides) == 0: document = self._remove_section(document, "ephemerides") if len(self.events) == 0: @@ -301,6 +301,9 @@ class LatexDumper(Dumper): def add_strings( self, document: str, kosmorro_logo_path: str, moon_phase_graphics: str ) -> str: + document = document.replace( + "+++CURRENT-DATE+++", datetime.datetime.now().isoformat() + ) document = document.replace("+++KOSMORRO-VERSION+++", KOSMORRO_VERSION) document = document.replace("+++KOSMORRO-LOGO+++", kosmorro_logo_path) document = document.replace("+++DOCUMENT-TITLE+++", _("Overview of your sky")) @@ -466,3 +469,76 @@ class LatexDumper(Dumper): new_document.append(line) return "\n".join(new_document) + + +class PdfDumper(Dumper): + def to_string(self): + try: + latex_dumper = LatexDumper( + self.ephemerides, + self.moon_phase, + self.events, + date=self.date, + timezone=self.timezone, + with_colors=self.with_colors, + show_graph=self.show_graph, + ) + + return self._compile(latex_dumper.to_string()) + except RuntimeError as error: + raise KosmorroUnavailableFeatureError( + _( + "Building PDF was not possible, because some dependencies are not" + " installed.\nPlease look at the documentation at https://kosmorro.space/cli/generate-pdf/ " + "for more information." + ) + ) from error + + @staticmethod + def is_file_output_needed() -> bool: + return True + + @staticmethod + def _compile(latex_input) -> bytes: + timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S") + current_dir = ( + os.getcwd() + ) # Keep the current directory to return to it after the PDFLaTeX execution + + try: + temp_dir = tempfile.mkdtemp() + temp_tex = "%s/%s.tex" % (temp_dir, timestamp) + + with open(temp_tex, "w") as tex_file: + tex_file.write(latex_input) + + os.chdir(temp_dir) + debug_print("LaTeX content:\n%s" % latex_input) + + subprocess.run( + ["pdflatex", "-interaction", "nonstopmode", "%s.tex" % timestamp], + capture_output=True, + check=True, + ) + + os.chdir(current_dir) + + with open("%s/%s.pdf" % (temp_dir, timestamp), "rb") as pdffile: + return bytes(pdffile.read()) + + except FileNotFoundError as error: + raise KosmorroUnavailableFeatureError( + "TeXLive is not installed." + ) from error + + except subprocess.CalledProcessError as error: + with open("/tmp/kosmorro-%s.log" % timestamp, "wb") as file: + file.write(error.stdout) + + raise CompileError( + _( + "An error occurred during the compilation of the PDF.\n" + "Please open an issue at https://github.com/Kosmorro/kosmorro/issues and share " + "the content of the log file at /tmp/kosmorro-%s.log" % timestamp + ) + ) from error diff --git a/kosmorro/locales/messages.pot b/kosmorro/locales/messages.pot index 4f56d1a..77a28d6 100644 --- a/kosmorro/locales/messages.pot +++ b/kosmorro/locales/messages.pot @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: PROJECT VERSION\n" "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" -"POT-Creation-Date: 2025-10-05 10:30+0200\n" +"POT-Creation-Date: 2025-10-19 16:22+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -17,80 +17,87 @@ msgstr "" "Content-Transfer-Encoding: 8bit\n" "Generated-By: Babel 2.17.0\n" -#: kosmorro/__main__.py:90 +#: kosmorro/__main__.py:89 msgid "" -"Output file will not contain the ephemerides, because you didn't provide " +"Save the planet and paper!\n" +"Consider printing your PDF document only if really necessary, and use the" +" other side of the sheet." +msgstr "" + +#: kosmorro/__main__.py:97 +msgid "" +"PDF output will not contain the ephemerides, because you didn't provide " "the observation coordinates." msgstr "" -#: kosmorro/__main__.py:108 +#: kosmorro/__main__.py:115 msgid "" "Environment variable KOSMORRO_TIMEZONE is deprecated. Use TZ instead, " "which is more standard." msgstr "" -#: kosmorro/__main__.py:117 +#: kosmorro/__main__.py:124 #, python-brace-format msgid "Unknown timezone: {timezone}" msgstr "" -#: kosmorro/__main__.py:160 +#: kosmorro/__main__.py:167 #, python-brace-format msgid "The file could not be saved in \"{path}\": {error}" msgstr "" -#: kosmorro/__main__.py:174 +#: kosmorro/__main__.py:181 msgid "Please provide a file path to export in this format (--output)." msgstr "" -#: kosmorro/__main__.py:206 +#: kosmorro/__main__.py:213 #, python-brace-format msgid "Moon phase can only be computed between {min_date} and {max_date}" msgstr "" -#: kosmorro/__main__.py:253 +#: kosmorro/__main__.py:264 #, python-brace-format msgid "Running on Python {python_version} with Kosmorrolib v{kosmorrolib_version}" msgstr "" -#: kosmorro/__main__.py:266 +#: kosmorro/__main__.py:277 msgid "" "Compute the ephemerides and the events for a given date and a given " "position on Earth." msgstr "" -#: kosmorro/__main__.py:269 +#: kosmorro/__main__.py:280 msgid "" "By default, only the events will be computed for today.\n" "To compute also the ephemerides, latitude and longitude arguments are " "needed." msgstr "" -#: kosmorro/__main__.py:281 +#: kosmorro/__main__.py:292 msgid "Show the program version" msgstr "" -#: kosmorro/__main__.py:290 +#: kosmorro/__main__.py:301 msgid "" "The format to output the information to. If not provided, the output " "format will be inferred from the file extension of the output file." msgstr "" -#: kosmorro/__main__.py:300 +#: kosmorro/__main__.py:311 #, python-brace-format msgid "" "The observer's position on Earth, in the \"{latitude},{longitude}\" " "format. Can also be set in the KOSMORRO_POSITION environment variable." msgstr "" -#: kosmorro/__main__.py:310 +#: kosmorro/__main__.py:321 msgid "" "The date for which the ephemerides must be calculated. Can be in the " "YYYY-MM-DD format or an interval in the \"[+-]YyMmDd\" format (with Y, M," " and D numbers). Defaults to current date." msgstr "" -#: kosmorro/__main__.py:321 +#: kosmorro/__main__.py:332 msgid "" "The timezone to use to display the hours. It can be either a number (e.g." " 1 for UTC+1) or a timezone name (e.g. Europe/Paris). See " @@ -98,29 +105,31 @@ msgid "" " timezone. Can also be set in the TZ environment variable." msgstr "" -#: kosmorro/__main__.py:330 +#: kosmorro/__main__.py:341 msgid "Disable the colors in the console." msgstr "" -#: kosmorro/__main__.py:338 -msgid "A file to export the output to. If not given, the standard output is used." +#: kosmorro/__main__.py:349 +msgid "" +"A file to export the output to. If not given, the standard output is " +"used. This argument is needed for PDF format." msgstr "" -#: kosmorro/__main__.py:346 +#: kosmorro/__main__.py:358 msgid "" "Do not generate a graph to represent the rise and set times in the LaTeX " -"file." +"or PDF file." msgstr "" -#: kosmorro/__main__.py:353 +#: kosmorro/__main__.py:365 msgid "Show debugging messages" msgstr "" -#: kosmorro/__main__.py:361 +#: kosmorro/__main__.py:373 msgid "Print a script allowing completion for your shell" msgstr "" -#: kosmorro/__main__.py:371 +#: kosmorro/__main__.py:383 msgid "No completion script available for this shell." msgstr "" @@ -149,19 +158,19 @@ msgstr "" msgid "Note: All the hours are given in the UTC{offset} timezone." msgstr "" -#: kosmorro/dumper.py:205 kosmorro/dumper.py:333 +#: kosmorro/dumper.py:205 kosmorro/dumper.py:336 msgid "Object" msgstr "" -#: kosmorro/dumper.py:206 kosmorro/dumper.py:334 +#: kosmorro/dumper.py:206 kosmorro/dumper.py:337 msgid "Rise time" msgstr "" -#: kosmorro/dumper.py:207 kosmorro/dumper.py:336 +#: kosmorro/dumper.py:207 kosmorro/dumper.py:339 msgid "Culmination time" msgstr "" -#: kosmorro/dumper.py:208 kosmorro/dumper.py:338 +#: kosmorro/dumper.py:208 kosmorro/dumper.py:341 msgid "Set time" msgstr "" @@ -174,11 +183,11 @@ msgstr "" msgid "{next_moon_phase} on {next_moon_phase_date} at {next_moon_phase_time}" msgstr "" -#: kosmorro/dumper.py:306 +#: kosmorro/dumper.py:309 msgid "Overview of your sky" msgstr "" -#: kosmorro/dumper.py:315 +#: kosmorro/dumper.py:318 #, python-brace-format msgid "" "This document summarizes the ephemerides and the events of {date}. It " @@ -186,28 +195,44 @@ msgid "" "given in {timezone}." msgstr "" -#: kosmorro/dumper.py:325 +#: kosmorro/dumper.py:328 msgid "" "Don't forget to check the weather forecast before you go out with your " "equipment." msgstr "" -#: kosmorro/dumper.py:331 +#: kosmorro/dumper.py:334 msgid "Ephemerides of the day" msgstr "" -#: kosmorro/dumper.py:340 +#: kosmorro/dumper.py:343 msgid "hours" msgstr "" -#: kosmorro/dumper.py:342 +#: kosmorro/dumper.py:345 msgid "Moon phase:" msgstr "" -#: kosmorro/dumper.py:347 +#: kosmorro/dumper.py:350 msgid "Expected events" msgstr "" +#: kosmorro/dumper.py:491 +msgid "" +"Building PDF was not possible, because some dependencies are not " +"installed.\n" +"Please look at the documentation at https://kosmorro.space/cli/generate-" +"pdf/ for more information." +msgstr "" + +#: kosmorro/dumper.py:540 +#, python-format +msgid "" +"An error occurred during the compilation of the PDF.\n" +"Please open an issue at https://github.com/Kosmorro/kosmorro/issues and " +"share the content of the log file at /tmp/kosmorro-%s.log" +msgstr "" + #: kosmorro/exceptions.py:36 #, python-brace-format msgid "The date must be between {minimum_date} and {maximum_date}" diff --git a/manpage/kosmorro.1.md b/manpage/kosmorro.1.md index 3a5db54..fbf0ddd 100644 --- a/manpage/kosmorro.1.md +++ b/manpage/kosmorro.1.md @@ -33,11 +33,11 @@ `--format=`_FORMAT_, `-f` _FORMAT_ (optional) the format under which the information have to be output; one of the following: - text (plain text, like normal console output), json, tex (LaTeX). + text (plain text, like normal console output), json, tex (LaTeX), pdf. If no format is provided, the output format will be inferred from the extension of the output file `--no-graph` - present the ephemerides in a table instead of a graph; LaTeX output format only + present the ephemerides in a table instead of a graph; PDF output format only `--completion [SHELL]` generate completion scripts for the specified shell (bash, zsh, fish, powershell) @@ -73,6 +73,12 @@ Compute the ephemerides for Lille, France, on April 1st, 2022: kosmorro --latitude=50.5876 --longitude=3.0624 --date=2022-04-01 ``` +Compute the ephemerides for Lille, France, on April 1st, 2022, and export them in a PDF document: + +``` +kosmorro --latitude=50.5876 --longitude=3.0624 -date=2022-04-01 --output=file.pdf +``` + ## AUTHOR Written by Jérôme Deuchnord. diff --git a/tests/general.py b/tests/general.py index 6716f7b..3ef6f34 100644 --- a/tests/general.py +++ b/tests/general.py @@ -39,7 +39,7 @@ def test_help_message(): if python_version.major == 3 and python_version.minor < 13: assert ( result.stdout - == """usage: kosmorro [-h] [--version] [--format {txt,json,tex}] + == """usage: kosmorro [-h] [--version] [--format {txt,json,pdf,tex}] [--position POSITION] [--date DATE] [--timezone TIMEZONE] [--no-colors] [--output OUTPUT] [--no-graph] [--debug] [--completion COMPLETION] @@ -50,7 +50,7 @@ on Earth. options: -h, --help show this help message and exit --version, -v Show the program version - --format {txt,json,tex}, -f {txt,json,tex} + --format {txt,json,pdf,tex}, -f {txt,json,pdf,tex} The format to output the information to. If not provided, the output format will be inferred from the file extension of the output file. @@ -71,9 +71,10 @@ options: --no-colors Disable the colors in the console. --output OUTPUT, -o OUTPUT A file to export the output to. If not given, the - standard output is used. + standard output is used. This argument is needed for + PDF format. --no-graph Do not generate a graph to represent the rise and set - times in the LaTeX file. + times in the LaTeX or PDF file. --debug Show debugging messages --completion COMPLETION Print a script allowing completion for your shell @@ -85,7 +86,7 @@ ephemerides, latitude and longitude arguments are needed. else: assert ( result.stdout - == """usage: kosmorro [-h] [--version] [--format {txt,json,tex}] + == """usage: kosmorro [-h] [--version] [--format {txt,json,pdf,tex}] [--position POSITION] [--date DATE] [--timezone TIMEZONE] [--no-colors] [--output OUTPUT] [--no-graph] [--debug] [--completion COMPLETION] @@ -96,7 +97,7 @@ on Earth. options: -h, --help show this help message and exit --version, -v Show the program version - --format, -f {txt,json,tex} + --format, -f {txt,json,pdf,tex} The format to output the information to. If not provided, the output format will be inferred from the file extension of the output file. @@ -116,9 +117,10 @@ options: Can also be set in the TZ environment variable. --no-colors Disable the colors in the console. --output, -o OUTPUT A file to export the output to. If not given, the - standard output is used. + standard output is used. This argument is needed for + PDF format. --no-graph Do not generate a graph to represent the rise and set - times in the LaTeX file. + times in the LaTeX or PDF file. --debug Show debugging messages --completion COMPLETION Print a script allowing completion for your shell diff --git a/tests/output.py b/tests/output.py index 30c80cb..b239920 100644 --- a/tests/output.py +++ b/tests/output.py @@ -5,8 +5,9 @@ from .utils import ( execute, KOSMORRO, ) - -from os import path +import tempfile +from os import path, environ +from sys import platform def test_json_output():