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.
 
 
 
 

394 lines
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. from pathlib import Path
  22. from tabulate import tabulate
  23. from numpy import int64
  24. from termcolor import colored
  25. from .data import ASTERS, Object, AsterEphemerides, MoonPhase, Event
  26. from .i18n import _
  27. from .version import VERSION
  28. from .exceptions import UnavailableFeatureError
  29. try:
  30. from latex import build_pdf
  31. except ImportError:
  32. build_pdf = None
  33. FULL_DATE_FORMAT = _('{day_of_week} {month} {day_number}, {year}').format(day_of_week='%A', month='%B',
  34. day_number='%d', year='%Y')
  35. SHORT_DATETIME_FORMAT = _('{month} {day_number}, {hours}:{minutes}').format(month='%b', day_number='%d',
  36. hours='%H', minutes='%M')
  37. TIME_FORMAT = _('{hours}:{minutes}').format(hours='%H', minutes='%M')
  38. class Dumper(ABC):
  39. def __init__(self, ephemerides: [AsterEphemerides] = None, moon_phase: MoonPhase = None, events: [Event] = None,
  40. date: datetime.date = datetime.date.today(), timezone: int = 0, with_colors: bool = True,
  41. show_graph: bool = False):
  42. self.ephemerides = ephemerides
  43. self.moon_phase = moon_phase
  44. self.events = events
  45. self.date = date
  46. self.timezone = timezone
  47. self.with_colors = with_colors
  48. self.show_graph = show_graph
  49. def get_date_as_string(self, capitalized: bool = False) -> str:
  50. date = self.date.strftime(FULL_DATE_FORMAT)
  51. if capitalized:
  52. return ''.join([date[0].upper(), date[1:]])
  53. return date
  54. @abstractmethod
  55. def to_string(self):
  56. pass
  57. @staticmethod
  58. def is_file_output_needed() -> bool:
  59. return False
  60. class JsonDumper(Dumper):
  61. def to_string(self):
  62. return json.dumps({
  63. 'ephemerides': [ephemeris.serialize() for ephemeris in self.ephemerides],
  64. 'moon_phase': self.moon_phase.serialize(),
  65. 'events': [event.serialize() for event in self.events]
  66. }, indent=4)
  67. @staticmethod
  68. def _json_default(obj):
  69. # Fixes the "TypeError: Object of type int64 is not JSON serializable"
  70. # See https://stackoverflow.com/a/50577730
  71. if isinstance(obj, int64):
  72. return int(obj)
  73. if isinstance(obj, datetime.datetime):
  74. return obj.isoformat()
  75. if isinstance(obj, Object):
  76. obj = obj.__dict__
  77. obj.pop('skyfield_name')
  78. obj.pop('radius')
  79. obj['object'] = obj.pop('name')
  80. obj['details'] = obj.pop('ephemerides')
  81. return obj
  82. if isinstance(obj, AsterEphemerides):
  83. return obj.__dict__
  84. if isinstance(obj, MoonPhase):
  85. moon_phase = obj.__dict__
  86. moon_phase['phase'] = moon_phase.pop('identifier')
  87. moon_phase['date'] = moon_phase.pop('time')
  88. return moon_phase
  89. if isinstance(obj, Event):
  90. event = obj.__dict__
  91. event['objects'] = [object.name for object in event['objects']]
  92. return event
  93. raise TypeError('Object of type "%s" could not be integrated in the JSON' % str(type(obj)))
  94. class TextDumper(Dumper):
  95. def to_string(self):
  96. text = [self.style(self.get_date_as_string(capitalized=True), 'h1')]
  97. if self.ephemerides is not None:
  98. text.append(self.stringify_ephemerides())
  99. text.append(self.get_moon(self.moon_phase))
  100. if len(self.events) > 0:
  101. text.append('\n'.join([self.style(_('Expected events:'), 'h2'),
  102. self.get_events(self.events)]))
  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(self.style(_('Note: All the hours are given in the UTC{offset} timezone.').format(
  110. offset=tz_offset), 'em'))
  111. return '\n\n'.join(text)
  112. def style(self, text: str, tag: str) -> str:
  113. if not self.with_colors:
  114. return text
  115. styles = {
  116. 'h1': lambda t: colored(t, 'yellow', attrs=['bold']),
  117. 'h2': lambda t: colored(t, 'magenta', attrs=['bold']),
  118. 'th': lambda t: colored(t, 'white', attrs=['bold']),
  119. 'strong': lambda t: colored(t, attrs=['bold']),
  120. 'em': lambda t: colored(t, attrs=['dark'])
  121. }
  122. return styles[tag](text)
  123. def stringify_ephemerides(self) -> str:
  124. data = []
  125. for ephemeris in self.ephemerides:
  126. name = self.style(ephemeris.object.name, 'th')
  127. if ephemeris.rise_time is not None:
  128. time_fmt = TIME_FORMAT if ephemeris.rise_time.day == self.date.day else SHORT_DATETIME_FORMAT
  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 = TIME_FORMAT if ephemeris.culmination_time.day == self.date.day \
  134. else SHORT_DATETIME_FORMAT
  135. planet_culmination = ephemeris.culmination_time.strftime(time_fmt)
  136. else:
  137. planet_culmination = '-'
  138. if ephemeris.set_time is not None:
  139. time_fmt = TIME_FORMAT if ephemeris.set_time.day == self.date.day else SHORT_DATETIME_FORMAT
  140. planet_set = ephemeris.set_time.strftime(time_fmt)
  141. else:
  142. planet_set = '-'
  143. data.append([name, planet_rise, planet_culmination, planet_set])
  144. return tabulate(data, headers=[self.style(_('Object'), 'th'),
  145. self.style(_('Rise time'), 'th'),
  146. self.style(_('Culmination time'), 'th'),
  147. self.style(_('Set time'), 'th')],
  148. tablefmt='simple', stralign='center', colalign=('left',))
  149. def get_events(self, events: [Event]) -> str:
  150. data = []
  151. for event in events:
  152. time_fmt = TIME_FORMAT if event.start_time.day == self.date.day else SHORT_DATETIME_FORMAT
  153. data.append([self.style(event.start_time.strftime(time_fmt), 'th'),
  154. event.get_description()])
  155. return tabulate(data, tablefmt='plain', stralign='left')
  156. def get_moon(self, moon_phase: MoonPhase) -> str:
  157. current_moon_phase = ' '.join([self.style(_('Moon phase:'), 'strong'), moon_phase.get_phase()])
  158. new_moon_phase = _('{next_moon_phase} on {next_moon_phase_date} at {next_moon_phase_time}').format(
  159. next_moon_phase=moon_phase.get_next_phase_name(),
  160. next_moon_phase_date=moon_phase.next_phase_date.strftime(FULL_DATE_FORMAT),
  161. next_moon_phase_time=moon_phase.next_phase_date.strftime(TIME_FORMAT)
  162. )
  163. return '\n'.join([current_moon_phase, new_moon_phase])
  164. class _LatexDumper(Dumper):
  165. def to_string(self):
  166. template_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
  167. 'assets', 'pdf', 'template.tex')
  168. with open(template_path, mode='r') as file:
  169. template = file.read()
  170. return self._make_document(template)
  171. def _make_document(self, template: str) -> str:
  172. kosmorro_logo_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
  173. 'assets', 'png', 'kosmorro-logo.png')
  174. moon_phase_graphics = os.path.join(os.path.abspath(os.path.dirname(__file__)),
  175. 'assets', 'moonphases', 'png',
  176. '.'.join([self.moon_phase.identifier.lower().replace('_', '-'),
  177. 'png']))
  178. document = template
  179. if self.ephemerides is None:
  180. document = self._remove_section(document, 'ephemerides')
  181. if len(self.events) == 0:
  182. document = self._remove_section(document, 'events')
  183. document = self.add_strings(document, kosmorro_logo_path, moon_phase_graphics)
  184. if self.show_graph:
  185. # The graphephemerides environment beginning tag must end with a percent symbol to ensure
  186. # that no extra space will interfere with the graph.
  187. document = document.replace(r'\begin{ephemerides}', r'\begin{graphephemerides}%')\
  188. .replace(r'\end{ephemerides}', r'\end{graphephemerides}')
  189. return document
  190. def add_strings(self, document, kosmorro_logo_path, moon_phase_graphics) -> str:
  191. document = document \
  192. .replace('+++KOSMORRO-VERSION+++', VERSION) \
  193. .replace('+++KOSMORRO-LOGO+++', kosmorro_logo_path) \
  194. .replace('+++DOCUMENT-TITLE+++', _('A Summary of your Sky')) \
  195. .replace('+++DOCUMENT-DATE+++', self.get_date_as_string(capitalized=True)) \
  196. .replace('+++INTRODUCTION+++',
  197. '\n\n'.join([
  198. _("This document summarizes the ephemerides and the events of {date}. "
  199. "It aims to help you to prepare your observation session. "
  200. "All the hours are given in {timezone}.").format(
  201. date=self.get_date_as_string(),
  202. timezone='UTC+%d' % self.timezone if self.timezone != 0 else 'UTC'
  203. ),
  204. _("Don't forget to check the weather forecast before you go out with your equipment.")
  205. ])) \
  206. .replace('+++SECTION-EPHEMERIDES+++', _('Ephemerides of the day')) \
  207. .replace('+++EPHEMERIDES-OBJECT+++', _('Object')) \
  208. .replace('+++EPHEMERIDES-RISE-TIME+++', _('Rise time')) \
  209. .replace('+++EPHEMERIDES-CULMINATION-TIME+++', _('Culmination time')) \
  210. .replace('+++EPHEMERIDES-SET-TIME+++', _('Set time')) \
  211. .replace('+++EPHEMERIDES+++', self._make_ephemerides()) \
  212. .replace('+++GRAPH_LABEL_HOURS+++', _('hours')) \
  213. .replace('+++MOON-PHASE-GRAPHICS+++', moon_phase_graphics) \
  214. .replace('+++CURRENT-MOON-PHASE-TITLE+++', _('Moon phase:')) \
  215. .replace('+++CURRENT-MOON-PHASE+++', self.moon_phase.get_phase()) \
  216. .replace('+++SECTION-EVENTS+++', _('Expected events')) \
  217. .replace('+++EVENTS+++', self._make_events())
  218. for aster in ASTERS:
  219. document = document.replace('+++ASTER_%s+++' % aster.skyfield_name.upper().split(' ')[0],
  220. aster.name)
  221. return document
  222. def _make_ephemerides(self) -> str:
  223. latex = []
  224. graph_y_component = 18
  225. if self.ephemerides is not None:
  226. for ephemeris in self.ephemerides:
  227. if ephemeris.rise_time is not None:
  228. time_fmt = TIME_FORMAT if ephemeris.rise_time.day == self.date.day else SHORT_DATETIME_FORMAT
  229. aster_rise = ephemeris.rise_time.strftime(time_fmt)
  230. else:
  231. aster_rise = '-'
  232. if ephemeris.culmination_time is not None:
  233. time_fmt = TIME_FORMAT if ephemeris.culmination_time.day == self.date.day\
  234. else SHORT_DATETIME_FORMAT
  235. aster_culmination = ephemeris.culmination_time.strftime(time_fmt)
  236. else:
  237. aster_culmination = '-'
  238. if ephemeris.set_time is not None:
  239. time_fmt = TIME_FORMAT if ephemeris.set_time.day == self.date.day else SHORT_DATETIME_FORMAT
  240. aster_set = ephemeris.set_time.strftime(time_fmt)
  241. else:
  242. aster_set = '-'
  243. if not self.show_graph:
  244. latex.append(r'\object{%s}{%s}{%s}{%s}' % (ephemeris.object.name,
  245. aster_rise,
  246. aster_culmination,
  247. aster_set))
  248. else:
  249. if ephemeris.rise_time is not None:
  250. raise_hour = ephemeris.rise_time.hour
  251. raise_minute = ephemeris.rise_time.minute
  252. else:
  253. raise_hour = raise_minute = 0
  254. aster_rise = ''
  255. if ephemeris.set_time is not None:
  256. set_hour = ephemeris.set_time.hour
  257. set_minute = ephemeris.set_time.minute
  258. else:
  259. set_hour = 24
  260. set_minute = 0
  261. aster_set = ''
  262. sets_after_end = set_hour > raise_hour
  263. if not sets_after_end:
  264. latex.append(r'\graphobject{%d}{gray}{0}{0}{%d}{%d}{}{%s}' % (graph_y_component,
  265. set_hour,
  266. set_minute,
  267. aster_set))
  268. set_hour = 24
  269. set_minute = 0
  270. latex.append(r'\graphobject{%d}{gray}{%d}{%d}{%d}{%d}{%s}{%s}' % (
  271. graph_y_component,
  272. raise_hour,
  273. raise_minute,
  274. set_hour,
  275. set_minute,
  276. aster_rise,
  277. aster_set if sets_after_end else ''
  278. ))
  279. graph_y_component -= 2
  280. return ''.join(latex)
  281. def _make_events(self) -> str:
  282. latex = []
  283. for event in self.events:
  284. latex.append(r'\event{%s}{%s}' % (event.start_time.strftime(TIME_FORMAT),
  285. event.get_description()))
  286. return ''.join(latex)
  287. @staticmethod
  288. def _remove_section(document: str, section: str):
  289. begin_section_tag = '%%%%%% BEGIN-%s-SECTION' % section.upper()
  290. end_section_tag = '%%%%%% END-%s-SECTION' % section.upper()
  291. document = document.split('\n')
  292. new_document = []
  293. ignore_line = False
  294. for line in document:
  295. if begin_section_tag in line or end_section_tag in line:
  296. ignore_line = not ignore_line
  297. continue
  298. if ignore_line:
  299. continue
  300. new_document.append(line)
  301. return '\n'.join(new_document)
  302. class PdfDumper(Dumper):
  303. def to_string(self):
  304. try:
  305. latex_dumper = _LatexDumper(self.ephemerides, self.moon_phase, self.events,
  306. date=self.date, timezone=self.timezone, with_colors=self.with_colors,
  307. show_graph=self.show_graph)
  308. return self._compile(latex_dumper.to_string())
  309. except RuntimeError:
  310. raise UnavailableFeatureError(_("Building PDFs was not possible, because some dependencies are not"
  311. " installed.\nPlease look at the documentation at http://kosmorro.space "
  312. "for more information."))
  313. @staticmethod
  314. def is_file_output_needed() -> bool:
  315. return True
  316. @staticmethod
  317. def _compile(latex_input) -> bytes:
  318. if build_pdf is None:
  319. raise RuntimeError('Python latex module not found')
  320. package = str(Path(__file__).parent.absolute()) + '/assets/pdf/'
  321. return bytes(build_pdf(latex_input, [package]))