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.
 
 
 
 

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