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.
 
 
 
 

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