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.
 
 
 
 

472 line
16 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 _
  31. from .i18n import strings
  32. from .exceptions import (
  33. CompileError,
  34. UnavailableFeatureError as KosmorroUnavailableFeatureError,
  35. )
  36. from .debug import debug_print
  37. from .utils import KOSMORRO_VERSION
  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__)),
  213. "assets",
  214. "latex",
  215. "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+++", KOSMORRO_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. aster_rise = (
  312. "-"
  313. if ephemeris.rise_time is None
  314. else format_time(ephemeris.rise_time, "short")
  315. )
  316. aster_culmination = (
  317. "-"
  318. if ephemeris.culmination_time is None
  319. else format_time(ephemeris.culmination_time, "short")
  320. )
  321. aster_set = (
  322. "-"
  323. if ephemeris.set_time is None
  324. else format_time(ephemeris.set_time, "short")
  325. )
  326. if not self.show_graph:
  327. object_name = strings.from_object(ephemeris.object.identifier)
  328. if object_name is not None:
  329. latex.append(
  330. r"\object{%s}{%s}{%s}{%s}"
  331. % (
  332. object_name,
  333. aster_rise,
  334. aster_culmination,
  335. aster_set,
  336. )
  337. )
  338. else:
  339. if ephemeris.rise_time is not None:
  340. raise_hour = ephemeris.rise_time.hour
  341. raise_minute = ephemeris.rise_time.minute
  342. else:
  343. raise_hour = raise_minute = 0
  344. aster_rise = ""
  345. if ephemeris.set_time is not None:
  346. set_hour = ephemeris.set_time.hour
  347. set_minute = ephemeris.set_time.minute
  348. else:
  349. set_hour = 24
  350. set_minute = 0
  351. aster_set = ""
  352. sets_after_end = set_hour > raise_hour
  353. if not sets_after_end:
  354. latex.append(
  355. r"\graphobject{%d}{gray}{0}{0}{%d}{%d}{}{%s}"
  356. % (graph_y_component, set_hour, set_minute, aster_set)
  357. )
  358. set_hour = 24
  359. set_minute = 0
  360. latex.append(
  361. r"\graphobject{%d}{gray}{%d}{%d}{%d}{%d}{%s}{%s}"
  362. % (
  363. graph_y_component,
  364. raise_hour,
  365. raise_minute,
  366. set_hour,
  367. set_minute,
  368. aster_rise,
  369. aster_set if sets_after_end else "",
  370. )
  371. )
  372. graph_y_component -= 2
  373. return "".join(latex)
  374. def _make_events(self) -> str:
  375. latex = []
  376. for event in self.events:
  377. event_name = strings.from_event(event)
  378. if event_name is None:
  379. continue
  380. latex.append(
  381. r"\event{%s}{%s}" % (format_time(event.start_time, "short"), event_name)
  382. )
  383. return "".join(latex)
  384. @staticmethod
  385. def _remove_section(document: str, section: str):
  386. begin_section_tag = "%%%%%% BEGIN-%s-SECTION" % section.upper()
  387. end_section_tag = "%%%%%% END-%s-SECTION" % section.upper()
  388. document = document.split("\n")
  389. new_document = []
  390. ignore_line = False
  391. for line in document:
  392. if begin_section_tag in line or end_section_tag in line:
  393. ignore_line = not ignore_line
  394. continue
  395. if ignore_line:
  396. continue
  397. new_document.append(line)
  398. return "\n".join(new_document)