25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 

558 satır
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. 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 = self.date.strftime(FULL_DATE_FORMAT)
  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. def to_string(self):
  78. return json.dumps(
  79. {
  80. "ephemerides": [
  81. ephemeris.serialize() for ephemeris in self.ephemerides
  82. ],
  83. "moon_phase": self.moon_phase.serialize(),
  84. "events": [event.serialize() for event in self.events],
  85. },
  86. indent=4,
  87. )
  88. class TextDumper(Dumper):
  89. def to_string(self):
  90. text = [self.style(self.get_date_as_string(capitalized=True), "h1")]
  91. if len(self.ephemerides) > 0:
  92. text.append(self.stringify_ephemerides())
  93. text.append(self.get_moon(self.moon_phase))
  94. if len(self.events) > 0:
  95. text.append(
  96. "\n".join(
  97. [
  98. self.style(_("Expected events:"), "h2"),
  99. self.get_events(self.events),
  100. ]
  101. )
  102. )
  103. if self.timezone == 0:
  104. text.append(self.style(_("Note: All the hours are given in UTC."), "em"))
  105. else:
  106. tz_offset = str(self.timezone)
  107. if self.timezone > 0:
  108. tz_offset = "".join(["+", tz_offset])
  109. text.append(
  110. self.style(
  111. _(
  112. "Note: All the hours are given in the UTC{offset} timezone."
  113. ).format(offset=tz_offset),
  114. "em",
  115. )
  116. )
  117. return "\n\n".join(text)
  118. def style(self, text: str, tag: str) -> str:
  119. if not self.with_colors:
  120. return text
  121. styles = {
  122. "h1": lambda t: colored(t, "yellow", attrs=["bold"]),
  123. "h2": lambda t: colored(t, "magenta", attrs=["bold"]),
  124. "th": lambda t: colored(t, "white", attrs=["bold"]),
  125. "strong": lambda t: colored(t, attrs=["bold"]),
  126. "em": lambda t: colored(t, attrs=["dark"]),
  127. }
  128. return styles[tag](text)
  129. def stringify_ephemerides(self) -> str:
  130. data = []
  131. for ephemeris in self.ephemerides:
  132. object_name = strings.from_object(ephemeris.object.identifier)
  133. if object_name is None:
  134. continue
  135. name = self.style(object_name, "th")
  136. if ephemeris.rise_time is not None:
  137. time_fmt = (
  138. TIME_FORMAT
  139. if ephemeris.rise_time.day == self.date.day
  140. else SHORT_DATETIME_FORMAT
  141. )
  142. planet_rise = ephemeris.rise_time.strftime(time_fmt)
  143. else:
  144. planet_rise = "-"
  145. if ephemeris.culmination_time is not None:
  146. time_fmt = (
  147. TIME_FORMAT
  148. if ephemeris.culmination_time.day == self.date.day
  149. else SHORT_DATETIME_FORMAT
  150. )
  151. planet_culmination = ephemeris.culmination_time.strftime(time_fmt)
  152. else:
  153. planet_culmination = "-"
  154. if ephemeris.set_time is not None:
  155. time_fmt = (
  156. TIME_FORMAT
  157. if ephemeris.set_time.day == self.date.day
  158. else SHORT_DATETIME_FORMAT
  159. )
  160. planet_set = ephemeris.set_time.strftime(time_fmt)
  161. else:
  162. planet_set = "-"
  163. data.append([name, planet_rise, planet_culmination, planet_set])
  164. return tabulate(
  165. data,
  166. headers=[
  167. self.style(_("Object"), "th"),
  168. self.style(_("Rise time"), "th"),
  169. self.style(_("Culmination time"), "th"),
  170. self.style(_("Set time"), "th"),
  171. ],
  172. tablefmt="simple",
  173. stralign="center",
  174. colalign=("left",),
  175. )
  176. def get_events(self, events: [Event]) -> str:
  177. data = []
  178. for event in events:
  179. description = strings.from_event(event)
  180. time_fmt = (
  181. TIME_FORMAT
  182. if event.start_time.day == self.date.day
  183. else SHORT_DATETIME_FORMAT
  184. )
  185. data.append(
  186. [
  187. self.style(event.start_time.strftime(time_fmt), "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=moon_phase.next_phase_date.strftime(FULL_DATE_FORMAT),
  206. next_moon_phase_time=moon_phase.next_phase_date.strftime(TIME_FORMAT),
  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.skyfield_name.upper().split(" ")[0],
  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. if ephemeris.rise_time is not None:
  309. time_fmt = (
  310. TIME_FORMAT
  311. if ephemeris.rise_time.day == self.date.day
  312. else SHORT_DATETIME_FORMAT
  313. )
  314. aster_rise = ephemeris.rise_time.strftime(time_fmt)
  315. else:
  316. aster_rise = "-"
  317. if ephemeris.culmination_time is not None:
  318. time_fmt = (
  319. TIME_FORMAT
  320. if ephemeris.culmination_time.day == self.date.day
  321. else SHORT_DATETIME_FORMAT
  322. )
  323. aster_culmination = ephemeris.culmination_time.strftime(time_fmt)
  324. else:
  325. aster_culmination = "-"
  326. if ephemeris.set_time is not None:
  327. time_fmt = (
  328. TIME_FORMAT
  329. if ephemeris.set_time.day == self.date.day
  330. else SHORT_DATETIME_FORMAT
  331. )
  332. aster_set = ephemeris.set_time.strftime(time_fmt)
  333. else:
  334. aster_set = "-"
  335. if not self.show_graph:
  336. object_name = strings.from_object(ephemeris.object.identifier)
  337. if object_name is not None:
  338. latex.append(
  339. r"\object{%s}{%s}{%s}{%s}"
  340. % (
  341. object_name,
  342. aster_rise,
  343. aster_culmination,
  344. aster_set,
  345. )
  346. )
  347. else:
  348. if ephemeris.rise_time is not None:
  349. raise_hour = ephemeris.rise_time.hour
  350. raise_minute = ephemeris.rise_time.minute
  351. else:
  352. raise_hour = raise_minute = 0
  353. aster_rise = ""
  354. if ephemeris.set_time is not None:
  355. set_hour = ephemeris.set_time.hour
  356. set_minute = ephemeris.set_time.minute
  357. else:
  358. set_hour = 24
  359. set_minute = 0
  360. aster_set = ""
  361. sets_after_end = set_hour > raise_hour
  362. if not sets_after_end:
  363. latex.append(
  364. r"\graphobject{%d}{gray}{0}{0}{%d}{%d}{}{%s}"
  365. % (graph_y_component, set_hour, set_minute, aster_set)
  366. )
  367. set_hour = 24
  368. set_minute = 0
  369. latex.append(
  370. r"\graphobject{%d}{gray}{%d}{%d}{%d}{%d}{%s}{%s}"
  371. % (
  372. graph_y_component,
  373. raise_hour,
  374. raise_minute,
  375. set_hour,
  376. set_minute,
  377. aster_rise,
  378. aster_set if sets_after_end else "",
  379. )
  380. )
  381. graph_y_component -= 2
  382. return "".join(latex)
  383. def _make_events(self) -> str:
  384. latex = []
  385. for event in self.events:
  386. event_name = strings.from_event(event)
  387. if event_name is None:
  388. continue
  389. latex.append(
  390. r"\event{%s}{%s}" % (event.start_time.strftime(TIME_FORMAT), event_name)
  391. )
  392. return "".join(latex)
  393. @staticmethod
  394. def _remove_section(document: str, section: str):
  395. begin_section_tag = "%%%%%% BEGIN-%s-SECTION" % section.upper()
  396. end_section_tag = "%%%%%% END-%s-SECTION" % section.upper()
  397. document = document.split("\n")
  398. new_document = []
  399. ignore_line = False
  400. for line in document:
  401. if begin_section_tag in line or end_section_tag in line:
  402. ignore_line = not ignore_line
  403. continue
  404. if ignore_line:
  405. continue
  406. new_document.append(line)
  407. return "\n".join(new_document)
  408. class PdfDumper(Dumper):
  409. def to_string(self):
  410. try:
  411. latex_dumper = _LatexDumper(
  412. self.ephemerides,
  413. self.moon_phase,
  414. self.events,
  415. date=self.date,
  416. timezone=self.timezone,
  417. with_colors=self.with_colors,
  418. show_graph=self.show_graph,
  419. )
  420. return self._compile(latex_dumper.to_string())
  421. except RuntimeError as error:
  422. raise KosmorroUnavailableFeatureError(
  423. _(
  424. "Building PDF was not possible, because some dependencies are not"
  425. " installed.\nPlease look at the documentation at https://kosmorro.space/cli/generate-pdf/ "
  426. "for more information."
  427. )
  428. ) from error
  429. @staticmethod
  430. def is_file_output_needed() -> bool:
  431. return True
  432. @staticmethod
  433. def _compile(latex_input) -> bytes:
  434. package = str(Path(__file__).parent.absolute()) + "/assets/pdf/kosmorro.sty"
  435. timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
  436. current_dir = (
  437. os.getcwd()
  438. ) # Keep the current directory to return to it after the PDFLaTeX execution
  439. try:
  440. temp_dir = tempfile.mkdtemp()
  441. shutil.copy(package, temp_dir)
  442. temp_tex = "%s/%s.tex" % (temp_dir, timestamp)
  443. with open(temp_tex, "w") as tex_file:
  444. tex_file.write(latex_input)
  445. os.chdir(temp_dir)
  446. debug_print("LaTeX content:\n%s" % latex_input)
  447. subprocess.run(
  448. ["pdflatex", "-interaction", "nonstopmode", "%s.tex" % timestamp],
  449. capture_output=True,
  450. check=True,
  451. )
  452. os.chdir(current_dir)
  453. with open("%s/%s.pdf" % (temp_dir, timestamp), "rb") as pdffile:
  454. return bytes(pdffile.read())
  455. except FileNotFoundError as error:
  456. raise KosmorroUnavailableFeatureError(
  457. "TeXLive is not installed."
  458. ) from error
  459. except subprocess.CalledProcessError as error:
  460. with open("/tmp/kosmorro-%s.log" % timestamp, "wb") as file:
  461. file.write(error.stdout)
  462. raise CompileError(
  463. _(
  464. "An error occurred during the compilation of the PDF.\n"
  465. "Please open an issue at https://github.com/Kosmorro/kosmorro/issues and share "
  466. "the content of the log file at /tmp/kosmorro-%s.log" % timestamp
  467. )
  468. ) from error