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.
 
 
 
 

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