Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 

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