You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

543 lines
19 KiB

  1. #!/usr/bin/env python3
  2. # Kosmorro - Compute The Next Ephemerides
  3. # Copyright (C) 2019 Jérôme Deuchnord <jerome@deuchnord.fr>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Affero General Public License as
  7. # published by the Free Software Foundation, either version 3 of the
  8. # License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU Affero General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Affero General Public License
  16. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. from abc import ABC, abstractmethod
  18. import datetime
  19. import json
  20. import os
  21. import tempfile
  22. import subprocess
  23. import shutil
  24. from pathlib import Path
  25. from kosmorrolib.exceptions import UnavailableFeatureError
  26. from tabulate import tabulate
  27. from termcolor import colored
  28. from kosmorrolib import AsterEphemerides, Event
  29. from kosmorrolib.model import ASTERS, MoonPhase
  30. from .i18n.utils import _, FULL_DATE_FORMAT, SHORT_DATETIME_FORMAT, TIME_FORMAT
  31. from .i18n import strings
  32. from .__version__ import __version__ as version
  33. from .exceptions import (
  34. CompileError,
  35. UnavailableFeatureError as KosmorroUnavailableFeatureError,
  36. )
  37. from .debug import debug_print
  38. class Dumper(ABC):
  39. def __init__(
  40. self,
  41. ephemerides: [AsterEphemerides] = None,
  42. moon_phase: MoonPhase = None,
  43. events: [Event] = None,
  44. date: datetime.date = datetime.date.today(),
  45. timezone: int = 0,
  46. with_colors: bool = True,
  47. show_graph: bool = False,
  48. ):
  49. self.ephemerides = ephemerides
  50. self.moon_phase = moon_phase
  51. self.events = events
  52. self.date = date
  53. self.timezone = timezone
  54. self.with_colors = with_colors
  55. self.show_graph = show_graph
  56. def get_date_as_string(self, capitalized: bool = False) -> str:
  57. date = self.date.strftime(FULL_DATE_FORMAT)
  58. if capitalized:
  59. return "".join([date[0].upper(), date[1:]])
  60. return date
  61. def __str__(self):
  62. return self.to_string()
  63. @abstractmethod
  64. def to_string(self):
  65. pass
  66. @staticmethod
  67. def is_file_output_needed() -> bool:
  68. return False
  69. class JsonDumper(Dumper):
  70. def to_string(self):
  71. return json.dumps(
  72. {
  73. "ephemerides": [
  74. ephemeris.serialize() for ephemeris in self.ephemerides
  75. ],
  76. "moon_phase": self.moon_phase.serialize(),
  77. "events": [event.serialize() for event in self.events],
  78. },
  79. indent=4,
  80. )
  81. class TextDumper(Dumper):
  82. def to_string(self):
  83. text = [self.style(self.get_date_as_string(capitalized=True), "h1")]
  84. if self.ephemerides is not None:
  85. text.append(self.stringify_ephemerides())
  86. text.append(self.get_moon(self.moon_phase))
  87. if len(self.events) > 0:
  88. text.append(
  89. "\n".join(
  90. [
  91. self.style(_("Expected events:"), "h2"),
  92. self.get_events(self.events),
  93. ]
  94. )
  95. )
  96. if self.timezone == 0:
  97. text.append(self.style(_("Note: All the hours are given in UTC."), "em"))
  98. else:
  99. tz_offset = str(self.timezone)
  100. if self.timezone > 0:
  101. tz_offset = "".join(["+", tz_offset])
  102. text.append(
  103. self.style(
  104. _(
  105. "Note: All the hours are given in the UTC{offset} timezone."
  106. ).format(offset=tz_offset),
  107. "em",
  108. )
  109. )
  110. return "\n\n".join(text)
  111. def style(self, text: str, tag: str) -> str:
  112. if not self.with_colors:
  113. return text
  114. styles = {
  115. "h1": lambda t: colored(t, "yellow", attrs=["bold"]),
  116. "h2": lambda t: colored(t, "magenta", attrs=["bold"]),
  117. "th": lambda t: colored(t, "white", attrs=["bold"]),
  118. "strong": lambda t: colored(t, attrs=["bold"]),
  119. "em": lambda t: colored(t, attrs=["dark"]),
  120. }
  121. return styles[tag](text)
  122. def stringify_ephemerides(self) -> str:
  123. data = []
  124. for ephemeris in self.ephemerides:
  125. name = self.style(strings.from_object(ephemeris.object.identifier), "th")
  126. if ephemeris.rise_time is not None:
  127. time_fmt = (
  128. TIME_FORMAT
  129. if ephemeris.rise_time.day == self.date.day
  130. else SHORT_DATETIME_FORMAT
  131. )
  132. planet_rise = ephemeris.rise_time.strftime(time_fmt)
  133. else:
  134. planet_rise = "-"
  135. if ephemeris.culmination_time is not None:
  136. time_fmt = (
  137. TIME_FORMAT
  138. if ephemeris.culmination_time.day == self.date.day
  139. else SHORT_DATETIME_FORMAT
  140. )
  141. planet_culmination = ephemeris.culmination_time.strftime(time_fmt)
  142. else:
  143. planet_culmination = "-"
  144. if ephemeris.set_time is not None:
  145. time_fmt = (
  146. TIME_FORMAT
  147. if ephemeris.set_time.day == self.date.day
  148. else SHORT_DATETIME_FORMAT
  149. )
  150. planet_set = ephemeris.set_time.strftime(time_fmt)
  151. else:
  152. planet_set = "-"
  153. data.append([name, planet_rise, planet_culmination, planet_set])
  154. return tabulate(
  155. data,
  156. headers=[
  157. self.style(_("Object"), "th"),
  158. self.style(_("Rise time"), "th"),
  159. self.style(_("Culmination time"), "th"),
  160. self.style(_("Set time"), "th"),
  161. ],
  162. tablefmt="simple",
  163. stralign="center",
  164. colalign=("left",),
  165. )
  166. def get_events(self, events: [Event]) -> str:
  167. def get_event_description(ev: Event):
  168. description = strings.from_event(ev)
  169. if ev.details is not None:
  170. description += " ({:s})".format(ev.details)
  171. return description
  172. data = []
  173. for event in events:
  174. time_fmt = (
  175. TIME_FORMAT
  176. if event.start_time.day == self.date.day
  177. else SHORT_DATETIME_FORMAT
  178. )
  179. data.append(
  180. [
  181. self.style(event.start_time.strftime(time_fmt), "th"),
  182. get_event_description(event),
  183. ]
  184. )
  185. return tabulate(data, tablefmt="plain", stralign="left")
  186. def get_moon(self, moon_phase: MoonPhase) -> str:
  187. if moon_phase is None:
  188. return _("Moon phase is unavailable for this date.")
  189. current_moon_phase = " ".join(
  190. [
  191. self.style(_("Moon phase:"), "strong"),
  192. strings.from_moon_phase(moon_phase.phase_type),
  193. ]
  194. )
  195. new_moon_phase = _(
  196. "{next_moon_phase} on {next_moon_phase_date} at {next_moon_phase_time}"
  197. ).format(
  198. next_moon_phase=_(strings.from_moon_phase(moon_phase.get_next_phase())),
  199. next_moon_phase_date=moon_phase.next_phase_date.strftime(FULL_DATE_FORMAT),
  200. next_moon_phase_time=moon_phase.next_phase_date.strftime(TIME_FORMAT),
  201. )
  202. return "\n".join([current_moon_phase, new_moon_phase])
  203. class _LatexDumper(Dumper):
  204. def to_string(self):
  205. template_path = os.path.join(
  206. os.path.abspath(os.path.dirname(__file__)), "assets", "pdf", "template.tex"
  207. )
  208. with open(template_path, mode="r") as file:
  209. template = file.read()
  210. return self._make_document(template)
  211. def _make_document(self, template: str) -> str:
  212. kosmorro_logo_path = os.path.join(
  213. os.path.abspath(os.path.dirname(__file__)),
  214. "assets",
  215. "png",
  216. "kosmorro-logo.png",
  217. )
  218. moon_phase_graphics = os.path.join(
  219. os.path.abspath(os.path.dirname(__file__)),
  220. "assets",
  221. "moonphases",
  222. "png",
  223. ".".join(
  224. [self.moon_phase.phase_type.name.lower().replace("_", "-"), "png"]
  225. ),
  226. )
  227. document = template
  228. if self.ephemerides is None:
  229. document = self._remove_section(document, "ephemerides")
  230. if len(self.events) == 0:
  231. document = self._remove_section(document, "events")
  232. document = self.add_strings(document, kosmorro_logo_path, moon_phase_graphics)
  233. if self.show_graph:
  234. # The graphephemerides environment beginning tag must end with a percent symbol to ensure
  235. # that no extra space will interfere with the graph.
  236. document = document.replace(
  237. r"\begin{ephemerides}", r"\begin{graphephemerides}%"
  238. ).replace(r"\end{ephemerides}", r"\end{graphephemerides}")
  239. return document
  240. def add_strings(
  241. self, document: str, kosmorro_logo_path: str, moon_phase_graphics: str
  242. ) -> str:
  243. document = document.replace("+++KOSMORRO-VERSION+++", version)
  244. document = document.replace("+++KOSMORRO-LOGO+++", kosmorro_logo_path)
  245. document = document.replace("+++DOCUMENT-TITLE+++", _("Overview of your sky"))
  246. document = document.replace(
  247. "+++DOCUMENT-DATE+++", self.get_date_as_string(capitalized=True)
  248. )
  249. document = document.replace(
  250. "+++INTRODUCTION+++",
  251. "\n\n".join(
  252. [
  253. _(
  254. "This document summarizes the ephemerides and the events of {date}. "
  255. "It aims to help you to prepare your observation session. "
  256. "All the hours are given in {timezone}."
  257. ).format(
  258. date=self.get_date_as_string(),
  259. timezone="UTC+%d" % self.timezone
  260. if self.timezone != 0
  261. else "UTC",
  262. ),
  263. _(
  264. "Don't forget to check the weather forecast before you go out with your equipment."
  265. ),
  266. ]
  267. ),
  268. )
  269. document = document.replace(
  270. "+++SECTION-EPHEMERIDES+++", _("Ephemerides of the day")
  271. )
  272. document = document.replace("+++EPHEMERIDES-OBJECT+++", _("Object"))
  273. document = document.replace("+++EPHEMERIDES-RISE-TIME+++", _("Rise time"))
  274. document = document.replace(
  275. "+++EPHEMERIDES-CULMINATION-TIME+++", _("Culmination time")
  276. )
  277. document = document.replace("+++EPHEMERIDES-SET-TIME+++", _("Set time"))
  278. document = document.replace("+++EPHEMERIDES+++", self._make_ephemerides())
  279. document = document.replace("+++GRAPH_LABEL_HOURS+++", _("hours"))
  280. document = document.replace("+++MOON-PHASE-GRAPHICS+++", moon_phase_graphics)
  281. document = document.replace("+++CURRENT-MOON-PHASE-TITLE+++", _("Moon phase:"))
  282. document = document.replace(
  283. "+++CURRENT-MOON-PHASE+++",
  284. strings.from_moon_phase(self.moon_phase.phase_type),
  285. )
  286. document = document.replace("+++SECTION-EVENTS+++", _("Expected events"))
  287. document = document.replace("+++EVENTS+++", self._make_events())
  288. for aster in ASTERS:
  289. document = document.replace(
  290. "+++ASTER_%s+++" % aster.skyfield_name.upper().split(" ")[0],
  291. strings.from_object(aster.identifier),
  292. )
  293. return document
  294. def _make_ephemerides(self) -> str:
  295. latex = []
  296. graph_y_component = 18
  297. if self.ephemerides is not None:
  298. for ephemeris in self.ephemerides:
  299. if ephemeris.rise_time is not None:
  300. time_fmt = (
  301. TIME_FORMAT
  302. if ephemeris.rise_time.day == self.date.day
  303. else SHORT_DATETIME_FORMAT
  304. )
  305. aster_rise = ephemeris.rise_time.strftime(time_fmt)
  306. else:
  307. aster_rise = "-"
  308. if ephemeris.culmination_time is not None:
  309. time_fmt = (
  310. TIME_FORMAT
  311. if ephemeris.culmination_time.day == self.date.day
  312. else SHORT_DATETIME_FORMAT
  313. )
  314. aster_culmination = ephemeris.culmination_time.strftime(time_fmt)
  315. else:
  316. aster_culmination = "-"
  317. if ephemeris.set_time is not None:
  318. time_fmt = (
  319. TIME_FORMAT
  320. if ephemeris.set_time.day == self.date.day
  321. else SHORT_DATETIME_FORMAT
  322. )
  323. aster_set = ephemeris.set_time.strftime(time_fmt)
  324. else:
  325. aster_set = "-"
  326. if not self.show_graph:
  327. latex.append(
  328. r"\object{%s}{%s}{%s}{%s}"
  329. % (
  330. strings.from_object(ephemeris.object.identifier),
  331. aster_rise,
  332. aster_culmination,
  333. aster_set,
  334. )
  335. )
  336. else:
  337. if ephemeris.rise_time is not None:
  338. raise_hour = ephemeris.rise_time.hour
  339. raise_minute = ephemeris.rise_time.minute
  340. else:
  341. raise_hour = raise_minute = 0
  342. aster_rise = ""
  343. if ephemeris.set_time is not None:
  344. set_hour = ephemeris.set_time.hour
  345. set_minute = ephemeris.set_time.minute
  346. else:
  347. set_hour = 24
  348. set_minute = 0
  349. aster_set = ""
  350. sets_after_end = set_hour > raise_hour
  351. if not sets_after_end:
  352. latex.append(
  353. r"\graphobject{%d}{gray}{0}{0}{%d}{%d}{}{%s}"
  354. % (graph_y_component, set_hour, set_minute, aster_set)
  355. )
  356. set_hour = 24
  357. set_minute = 0
  358. latex.append(
  359. r"\graphobject{%d}{gray}{%d}{%d}{%d}{%d}{%s}{%s}"
  360. % (
  361. graph_y_component,
  362. raise_hour,
  363. raise_minute,
  364. set_hour,
  365. set_minute,
  366. aster_rise,
  367. aster_set if sets_after_end else "",
  368. )
  369. )
  370. graph_y_component -= 2
  371. return "".join(latex)
  372. def _make_events(self) -> str:
  373. latex = []
  374. for event in self.events:
  375. latex.append(
  376. r"\event{%s}{%s}"
  377. % (event.start_time.strftime(TIME_FORMAT), strings.from_event(event))
  378. )
  379. return "".join(latex)
  380. @staticmethod
  381. def _remove_section(document: str, section: str):
  382. begin_section_tag = "%%%%%% BEGIN-%s-SECTION" % section.upper()
  383. end_section_tag = "%%%%%% END-%s-SECTION" % section.upper()
  384. document = document.split("\n")
  385. new_document = []
  386. ignore_line = False
  387. for line in document:
  388. if begin_section_tag in line or end_section_tag in line:
  389. ignore_line = not ignore_line
  390. continue
  391. if ignore_line:
  392. continue
  393. new_document.append(line)
  394. return "\n".join(new_document)
  395. class PdfDumper(Dumper):
  396. def to_string(self):
  397. try:
  398. latex_dumper = _LatexDumper(
  399. self.ephemerides,
  400. self.moon_phase,
  401. self.events,
  402. date=self.date,
  403. timezone=self.timezone,
  404. with_colors=self.with_colors,
  405. show_graph=self.show_graph,
  406. )
  407. return self._compile(latex_dumper.to_string())
  408. except RuntimeError as error:
  409. raise KosmorroUnavailableFeatureError(
  410. _(
  411. "Building PDF was not possible, because some dependencies are not"
  412. " installed.\nPlease look at the documentation at https://kosmorro.space/cli/generate-pdf/ "
  413. "for more information."
  414. )
  415. ) from error
  416. @staticmethod
  417. def is_file_output_needed() -> bool:
  418. return True
  419. @staticmethod
  420. def _compile(latex_input) -> bytes:
  421. package = str(Path(__file__).parent.absolute()) + "/assets/pdf/kosmorro.sty"
  422. timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
  423. current_dir = (
  424. os.getcwd()
  425. ) # Keep the current directory to return to it after the PDFLaTeX execution
  426. try:
  427. temp_dir = tempfile.mkdtemp()
  428. shutil.copy(package, temp_dir)
  429. temp_tex = "%s/%s.tex" % (temp_dir, timestamp)
  430. with open(temp_tex, "w") as tex_file:
  431. tex_file.write(latex_input)
  432. os.chdir(temp_dir)
  433. debug_print("LaTeX content:\n%s" % latex_input)
  434. subprocess.run(
  435. ["pdflatex", "-interaction", "nonstopmode", "%s.tex" % timestamp],
  436. capture_output=True,
  437. check=True,
  438. )
  439. os.chdir(current_dir)
  440. with open("%s/%s.pdf" % (temp_dir, timestamp), "rb") as pdffile:
  441. return bytes(pdffile.read())
  442. except FileNotFoundError as error:
  443. raise KosmorroUnavailableFeatureError(
  444. "TeXLive is not installed."
  445. ) from error
  446. except subprocess.CalledProcessError as error:
  447. with open("/tmp/kosmorro-%s.log" % timestamp, "wb") as file:
  448. file.write(error.stdout)
  449. raise CompileError(
  450. _(
  451. "An error occurred during the compilation of the PDF.\n"
  452. "Please open an issue at https://github.com/Kosmorro/kosmorro/issues and share "
  453. "the content of the log file at /tmp/kosmorro-%s.log" % timestamp
  454. )
  455. ) from error