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.
 
 
 
 

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