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.
 
 
 
 

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