Пример #1
0
    def get_best_transliterated_name(self, scripts, fest_details_dict):
        names = self.get_human_names(fest_details_dict=fest_details_dict)
        languages = list(names.keys())
        language_scripts = [
            language_code_to_script.get(language, scripts[0])
            for language in languages
        ]
        for script in scripts:
            try:
                i = language_scripts.index(script)
                return {
                    "script":
                    script,
                    "text":
                    custom_transliteration.tr(text=names[languages[i]][0],
                                              script=script)
                }
            except ValueError:
                continue

        # No language text matching the input scripts was found.
        if "sa" in names:
            text = names["sa"][0]
        else:
            text = list(names.values())[0][0]
        return {
            "script": script,
            "text": custom_transliteration.tr(text=text, script=scripts[0])
        }
Пример #2
0
def get_chandra_masa(month, script, visarga=True):
    if visarga:
        if month == int(month):
            return NAMES["CHANDRA_MASA_NAMES"]["sa"][script][int(month)]
        else:
            return "%s-(%s)" % (NAMES["CHANDRA_MASA_NAMES"]["sa"][script][
                int(month) + 1], tr("adhikaH", script, titled=False))
    else:
        if month == int(month):
            return NAMES["CHANDRA_MASA_NAMES"]["sa"][script][int(month)][:-1]
        else:
            return "%s-(%s)" % (NAMES["CHANDRA_MASA_NAMES"]["sa"][script][
                int(month) + 1][:-1], tr("adhika", script, titled=False))
Пример #3
0
def get_chandra_masa(month, NAMES, script, visarga=True):
    if visarga:
        if month == int(month):
            return NAMES['CHANDRA_MASA_NAMES'][script][month]
        else:
            return '%s-(%s)' % (NAMES['CHANDRA_MASA_NAMES'][script][
                int(month) + 1], tr('adhikaH', script, titled=False))
    else:
        if month == int(month):
            return NAMES['CHANDRA_MASA_NAMES'][script][month][:-1]
        else:
            return '%s-(%s)' % (NAMES['CHANDRA_MASA_NAMES'][script][
                int(month) + 1][:-1], tr('adhika', script, titled=False))
Пример #4
0
    def get_description_string(self, script, include_url=False):
        description_string = ""
        if hasattr(self, "description"):
            # description_string = json.dumps(self.description)
            description_string = self.description["en"]
            pieces = description_string.split('`')
            if len(pieces) > 1:
                if len(pieces) % 2 == 1:
                    # We much have matching backquotes, the contents of which can be neatly transliterated
                    for i, piece in enumerate(pieces):
                        if (i % 2) == 1:
                            pieces[i] = custom_transliteration.tr(
                                piece, script, False)
                    description_string = ''.join(pieces)
                else:
                    logging.warning(
                        'Unmatched backquotes in description string: %s' %
                        description_string)
        if hasattr(self, "shlokas"):
            description_string = description_string + '\n\n' + custom_transliteration.tr(
                ", ".join(self.shlokas), script, False) + '\n\n'
        if include_url:
            base_url = 'https://github.com/sanskrit-coders/jyotisha/tree/master/jyotisha/panchangam/temporal/festival/data'
            if hasattr(self, "angam_type"):
                url = "%(base_dir)s/%(month_type)s/%(angam_type)s/%(month_number)02d/%(angam_number)02d#%(id)s" % dict(
                    base_dir=base_url,
                    month_type=self.month_type,
                    angam_type=self.angam_type,
                    month_number=self.month_number,
                    angam_number=self.angam_number,
                    id=self.id.replace('/', '').replace('ta:', '').replace(
                        ' ', '-').replace('~', '-').strip('{}').lower())
            elif hasattr(self, "anchor_festival_id"):
                url = "%(base_dir)s/relative_event/%(anchor_festival_id)s/offset__%(offset)02d#%(id)s" % dict(
                    base_dir=base_url,
                    anchor_festival_id=self.anchor_festival_id.replace(
                        '/', '__'),
                    offset=self.offset,
                    id=self.id.replace('/', '').replace('ta:', '').replace(
                        ' ', '-').replace('~', '-').strip('{}').lower())
            else:
                tag_list = ('/'.join(self.tags.split(',')))
                url = "%(base_dir)s/other/%(tags)s#%(id)s" % dict(
                    base_dir=base_url,
                    tags=tag_list,
                    id=self.id.replace('/', '').replace('ta:', '').replace(
                        ' ', '-').replace('~', '-').strip('{}').lower())

            return description_string + ('\n\n%s\n' % url)
        else:
            return description_string
Пример #5
0
 def tex_code(self, scripts, timezone, fest_details_dict):
   name_details = self.get_best_transliterated_name(scripts=scripts, fest_details_dict=fest_details_dict)
   if name_details["script"] == sanscript.TAMIL:
     name = '\\tamil{%s}' % name_details["text"]
   else:
     name = name_details["text"]
   return custom_transliteration.tr("%s~%s##\\To{}##%s" % (name, self.status_1_hk, self.status_2_hk), script=scripts[0])
Пример #6
0
def get_chandra_masa(month, NAMES, script):
    if month == int(month):
        return NAMES['CHANDRA_MASA_NAMES'][script][month]
    else:
        return '%s-(%s)' % (NAMES['CHANDRA_MASA_NAMES'][script][int(month) +
                                                                1],
                            tr('adhika', script))
Пример #7
0
    def tex_code(self,
                 languages,
                 scripts,
                 timezone,
                 fest_details_dict,
                 reference_date=None):
        name_details = self.get_best_transliterated_name(
            languages=languages,
            scripts=scripts,
            fest_details_dict=fest_details_dict)
        if name_details["script"] == sanscript.TAMIL:
            name = '\\tamil{%s}' % name_details["text"]
        else:
            name = name_details["text"]

        if self.ordinal is not None:
            name = name + "~\\#{%s}" % custom_transliteration.tr(
                str(self.ordinal), script=scripts[0])

        if self.interval is not None and self._show_interval():
            return "%s%s" % (name,
                             self.interval.to_hour_tex(
                                 script=scripts[0],
                                 tz=timezone,
                                 reference_date=reference_date))
        else:
            return name
Пример #8
0
 def get_description_string(self, script, includeShloka=False):
   # When used for README.md generation, shloka is included differently
   # When used for ICS generation, shloka can be included right here
   description_string = ""
   if hasattr(self, "description"):
     # description_string = json.dumps(self.description)
     description_string = self.description["en"]
     pieces = description_string.split('`')
     if len(pieces) > 1:
       if len(pieces) % 2 == 1:
         # We much have matching backquotes, the contents of which can be neatly transliterated
         for i, piece in enumerate(pieces):
           if (i % 2) == 1:
             pieces[i] = custom_transliteration.tr(piece, script, False)
         description_string = ''.join(pieces)
       else:
         logging.warning('Unmatched backquotes in description string: %s' % description_string)
   if includeShloka and hasattr(self, "shlokas"):
     description_string = description_string + '\n\n' + \
                          custom_transliteration.tr(", ".join(self.shlokas), script, False) + '\n\n'
   return description_string
Пример #9
0
 def get_full_title(self,
                    fest_details_dict,
                    languages=["sa"],
                    scripts=[xsanscript.DEVANAGARI]):
     name_details = self.get_best_transliterated_name(
         languages=languages,
         scripts=scripts,
         fest_details_dict=fest_details_dict)
     ordinal_str = " #%s" % custom_transliteration.tr(
         str(self.ordinal),
         script=name_details["script"]) if self.ordinal is not None else ""
     return "%s%s" % (name_details["text"].replace("~", "-"), ordinal_str)
Пример #10
0
def transliterate_quoted_text(text, script):
  transliterated_text = text
  pieces = transliterated_text.split('`')
  if len(pieces) > 1:
    if len(pieces) % 2 == 1:
      # We much have matching backquotes, the contents of which can be neatly transliterated
      for i, piece in enumerate(pieces):
        if (i % 2) == 1:
          pieces[i] = custom_transliteration.tr(piece, script, titled=True)
      transliterated_text = ''.join(pieces)
    else:
      logging.warning('Unmatched backquotes in string: %s' % transliterated_text)
  return transliterated_text
Пример #11
0
 def tex_code(self,
              languages,
              scripts,
              timezone,
              fest_details_dict,
              reference_date=None):
     name_details = self.get_best_transliterated_name(
         languages=languages,
         scripts=scripts,
         fest_details_dict=fest_details_dict)
     name = name_details["text"]
     return custom_transliteration.tr(
         "%s~(%s##\\To{}##%s)" % (name, self.status_1_hk, self.status_2_hk),
         script=scripts[0])
Пример #12
0
def festival_instance_to_event(festival_instance,
                               languages,
                               scripts,
                               panchaanga,
                               all_day=False):
    rules_collection = rules.RulesCollection.get_cached(
        repos_tuple=tuple(
            panchaanga.computation_system.festival_options.repos),
        julian_handling=panchaanga.computation_system.festival_options.
        julian_handling)
    fest_details_dict = rules_collection.name_to_rule
    fest_name = festival_instance.get_best_transliterated_name(
        languages=languages,
        scripts=scripts,
        fest_details_dict=rules_collection.name_to_rule)["text"].replace(
            "~", " ")
    if festival_instance.ordinal is not None:
        fest_name += ' #%s' % custom_transliteration.tr(
            str(festival_instance.ordinal), scripts[0])
    event = Event()
    event.add('summary', fest_name)
    desc = get_description(festival_instance=festival_instance,
                           script=scripts[0],
                           fest_details_dict=fest_details_dict,
                           header_md="##")
    event.add('description', desc.strip().replace('\n', '<br/>'))

    if all_day or not festival_instance._show_interval():
        t1 = panchaanga.city.get_timezone_obj().julian_day_to_local_datetime(
            jd=festival_instance.interval.jd_start)
        t2 = panchaanga.city.get_timezone_obj().julian_day_to_local_datetime(
            jd=festival_instance.interval.jd_end)
        event.add('dtstart', t1.date())
        event.add('dtend', t2.date())
        event['X-MICROSOFT-CDO-ALLDAYEVENT'] = 'TRUE'
        event['TRANSP'] = 'TRANSPARENT'
        event['X-MICROSOFT-CDO-BUSYSTATUS'] = 'FREE'
    elif festival_instance.interval is not None and festival_instance.interval.jd_end is not None and festival_instance.interval.jd_start is not None:
        # Starting or ending time is empty, e.g. harivasara, so no ICS entry
        t1 = panchaanga.city.get_timezone_obj().julian_day_to_local_datetime(
            jd=festival_instance.interval.jd_start)
        t2 = panchaanga.city.get_timezone_obj().julian_day_to_local_datetime(
            jd=festival_instance.interval.jd_end)
        event.add('dtstart', t1)
        event.add('dtend', t2)

    alarm = get_4_hr_display_alarm()
    event.add_component(alarm)
    return event
Пример #13
0
def get_english_description(description_string, rule):
  if "en" not in rule.description:
    return ""
  description_string += rule.description["en"]
  pieces = description_string.split('`')
  if len(pieces) > 1:
    if len(pieces) % 2 == 1:
      # We much have matching backquotes, the contents of which can be neatly transliterated
      for i, piece in enumerate(pieces):
        if (i % 2) == 1:
          pieces[i] = custom_transliteration.tr(piece, sanscript.ISO, False)
      description_string = ''.join(pieces)
    else:
      logging.warning('Unmatched backquotes in description string: %s' % description_string)
  return description_string
Пример #14
0
    def tex_code(self, scripts, timezone, fest_details_dict):
        name_details = self.get_best_transliterated_name(
            scripts=scripts, fest_details_dict=fest_details_dict)
        if name_details["script"] == sanscript.TAMIL:
            name = '\\tamil{%s}' % name_details["text"]
        else:
            name = name_details["text"]

        if self.ordinal is not None:
            name = name + "~\\#{%s}" % custom_transliteration.tr(
                str(self.ordinal), script=scripts[0])

        if self.interval is None:
            return name
        else:
            from jyotisha.panchaanga.temporal.time import Hour
            start_time_str = "" if self.interval.jd_start is None else Hour(
                timezone.julian_day_to_local_time(
                    self.interval.jd_start).get_fractional_hour()).toString()
            end_time_str = "" if self.interval.jd_end is None else Hour(
                timezone.julian_day_to_local_time(
                    self.interval.jd_end).get_fractional_hour()).toString()
            start_time_str = custom_transliteration.tr(text=start_time_str,
                                                       script=scripts[0])
            start_time_str = sanscript.transliterate(data=start_time_str,
                                                     _from=sanscript.HK,
                                                     _to=scripts[0])
            if start_time_str != "":
                start_time_str = "\\textsf{%s}" % start_time_str
            end_time_str = sanscript.transliterate(data=end_time_str,
                                                   _from=sanscript.HK,
                                                   _to=scripts[0])
            if end_time_str != "":
                end_time_str = "\\textsf{%s}" % end_time_str
            return "%s%s{\\RIGHTarrow}%s" % (name, start_time_str,
                                             end_time_str)
Пример #15
0
def get_raashi_data_str(daily_panchaanga, scripts, time_format):
  jd = daily_panchaanga.julian_day_start
  rashi_data_str = custom_transliteration.tr('candrarAziH—', scripts[0])
  for iRaashi, raashi_span in enumerate(daily_panchaanga.sunrise_day_angas.raashis_with_ends):
    if iRaashi == 0:
      (rashi_ID, rashi_end_jd) = (raashi_span.anga.index, raashi_span.jd_end)
      # if rashi_data_str != '':
      #     rashi_data_str += '\\hspace{1ex}'
      rashi = names.NAMES['RASHI_NAMES']['sa'][scripts[0]][rashi_ID]
      if rashi_end_jd is None:
        rashi_data_str = '%s\\mbox{%s}' % (rashi_data_str, rashi)
      else:
        rashi_data_str = '%s\\mbox{%s\\RIGHTarrow{%s}}' % \
                         (rashi_data_str, rashi,
                          time.Hour(24 * (rashi_end_jd - jd)).to_string(
                            format=time_format))
  return rashi_data_str
Пример #16
0
def write_event_README(event, event_file_name):
    with open(event_file_name) as event_data:
        readme_file_name = os.path.join(os.path.dirname(event_file_name),
                                        'README.md')
        event_dict = json.load(event_data)
        with open(readme_file_name, 'a+') as readme_file:
            headline = custom_transliteration.tr(
                event_dict["id"],
                sanscript.IAST).replace('Ta__', '').replace('~',
                                                            ' ').strip('{}')
            # Replace letter following r̂/r̂r̂ with lowercase
            for sep in ['r̂']:
                if headline[1:].find(sep) != -1:
                    headline = sep.join([
                        word[0].lower() + word[1:]
                        for word in headline.split(sep)
                    ])
                    headline = headline[0].upper() + headline[1:]
            for sep in ['r̂r̂']:
                if headline[1:].find(sep) != -1:
                    headline = sep.join([
                        word[0].lower() + word[1:]
                        for word in headline.split(sep)
                    ])
                    headline = headline[0].upper() + headline[1:]
            readme_file.write('## %s\n' % headline)

            blurb = ''
            month = ''
            angam = ''
            if 'month_type' in event_dict['timing']:
                if event_dict['timing']['month_type'] == 'lunar_month':
                    if event_dict['timing']['month_number'] == 0:
                        month = ' of every lunar month'
                    else:
                        month = ' of ' + get_chandra_masa(
                            event_dict['timing']['month_number'], NAMES,
                            sanscript.IAST) + ' (lunar) month'
                elif event_dict['timing']['month_type'] == 'solar_month':
                    if event_dict['timing']['month_number'] == 0:
                        month = ' of every solar month'
                    else:
                        month = ' of ' + NAMES['RASHI_NAMES'][sanscript.IAST][
                            event_dict['timing']
                            ['month_number']] + ' (solar) month'
            if 'angam_type' in event_dict['timing']:
                logging.debug(event_dict["id"])
                if event_dict["id"][:4] == "ta__":
                    angam = custom_transliteration.tr(
                        event_dict["id"][4:], sanscript.TAMIL).replace(
                            "~", " ").strip("{}") + ' is observed on '
                else:
                    angam = custom_transliteration.tr(
                        event_dict["id"], sanscript.DEVANAGARI).replace(
                            "~", " ") + ' is observed on '

                if event_dict['timing']['angam_type'] == 'tithi':
                    angam += NAMES['TITHI_NAMES'][sanscript.IAST][
                        event_dict['timing']['angam_number']] + ' tithi'
                elif event_dict['timing']['angam_type'] == 'nakshatram':
                    angam += NAMES['NAKSHATRAM_NAMES'][
                        sanscript.IAST][event_dict['timing']
                                        ['angam_number']] + ' nakṣhatram day'
                elif event_dict['timing']['angam_type'] == 'day':
                    angam += 'day %d' % event_dict['timing']['angam_number']
            else:
                logging.debug('No angam_type in %s', event_dict['id'])
            if 'kaala' in event_dict['timing']:
                kaala = event_dict["timing"]["kaala"]
            else:
                kaala = "sunrise (default)"
            if 'priority' in event_dict:
                priority = event_dict["priority"]
            else:
                priority = 'puurvaviddha (default)'
            if angam is not None:
                blurb += angam
            if month is not None:
                blurb += month
            if blurb != '':
                blurb += ' (%s/%s).\n\n' % (kaala, priority)
            readme_file.write(blurb)
            description_string = ""
            if "image" in event_dict:
                description_string = '![](https://github.com/sanskrit-coders/adyatithi/blob/master/images/%s)\n\n' % event_dict[
                    'image']

            if "description" in event_dict:
                # description_string = json.dumps(event_dict.description)
                # description_string = '_' + event_dict["description"]["en"] + '_'
                description_string = description_string + '_' + event.get_description_string(
                    script=sanscript.DEVANAGARI) + '_'
            if "shlokas" in event_dict:
                description_string = description_string + '\n\n```\n' + \
                                     custom_transliteration.tr(", ".join(event_dict["shlokas"]),
                                                               sanscript.DEVANAGARI, False) + '\n```'
            readme_file.write(description_string)
            if "references_primary" in event_dict or "references_secondary" in event_dict:
                readme_file.write('\n')
                readme_file.write('### References\n')
                if "references_primary" in event_dict:
                    for ref in event_dict["references_primary"]:
                        readme_file.write(
                            '* %s\n' %
                            transliterate_quoted_text(ref, sanscript.IAST))
                if "references_secondary" in event_dict:
                    for ref in event_dict["references_secondary"]:
                        readme_file.write(
                            '* %s\n' %
                            transliterate_quoted_text(ref, sanscript.IAST))
            readme_file.write('\n\n---\n')
Пример #17
0
 def get_transliterated_name(self, script):
   if self.name_hk is not None:
     return custom_transliteration.tr(self.name_hk, script)
   else:
     return self.name
Пример #18
0
    def get_description_string(self,
                               script,
                               include_url=False,
                               include_images=False,
                               use_markup=False,
                               include_shlokas=False,
                               is_brief=False):
        # Get the Blurb
        blurb = ''
        month = ''
        angam = ''
        if hasattr(self, "month_type"):
            if self.month_type == 'lunar_month':
                if self.month_number == 0:
                    month = ' of every lunar month'
                else:
                    month = ' of ' + get_chandra_masa(
                        self.month_number, NAMES,
                        sanscript.IAST) + ' (lunar) month'
            elif self.month_type == 'solar_month':
                if self.month_number == 0:
                    month = ' of every solar month'
                else:
                    month = ' of ' + NAMES['RASHI_NAMES'][sanscript.IAST][
                        self.month_number] + ' (solar) month'
        if hasattr(self, "angam_type"):
            logging.debug(self.id)
            if self.id[:4] == "ta__":
                angam = custom_transliteration.tr(
                    self.id[4:], sanscript.TAMIL).replace(
                        "~", " ").strip("{}") + ' is observed on '
            else:
                angam = custom_transliteration.tr(
                    self.id, sanscript.DEVANAGARI).replace(
                        "~", " ") + ' is observed on '

            if self.angam_type == 'tithi':
                angam += NAMES['TITHI_NAMES'][sanscript.IAST][
                    self.angam_number] + ' tithi'
            elif self.angam_type == 'nakshatram':
                angam += NAMES['NAKSHATRAM_NAMES'][sanscript.IAST][
                    self.angam_number] + ' nakṣhatram day'
            elif self.angam_type == 'day':
                angam += 'day %d' % self.angam_number
        else:
            if not hasattr(self, "description"):
                logging.debug("No angam_type in %s or description even!!",
                              self.id)
        if hasattr(self, "kaala"):
            kaala = self.kaala
        else:
            kaala = "sunrise (default)"
        if hasattr(self, "priority"):
            priority = self.priority
        else:
            priority = 'puurvaviddha (default)'
        if angam is not None:
            blurb += angam
        if month is not None:
            blurb += month
        if blurb != '':
            blurb += ' (%s/%s).\n' % (kaala, priority)

        # Get the URL
        if include_url:
            base_url = 'https://github.com/sanskrit-coders/adyatithi/tree/master/data'
            if hasattr(self, "angam_type"):
                url = "%(base_dir)s/%(month_type)s/%(angam_type)s/%(month_number)02d/%(angam_number)02d#%(id)s" % dict(
                    base_dir=base_url,
                    month_type=self.month_type,
                    angam_type=self.angam_type,
                    month_number=self.month_number,
                    angam_number=self.angam_number,
                    id=custom_transliteration.tr(
                        self.id, sanscript.IAST).replace('Ta__', '').replace(
                            '~', ' ').replace(' ', '-').replace(
                                '(', '').replace(')', '').strip('{}').lower())
            elif hasattr(self, "anchor_festival_id"):
                url = "%(base_dir)s/relative_event/%(anchor_festival_id)s/offset__%(offset)02d#%(id)s" % dict(
                    base_dir=base_url,
                    anchor_festival_id=self.anchor_festival_id.replace(
                        '/', '__'),
                    offset=self.offset,
                    id=custom_transliteration.tr(
                        self.id, sanscript.IAST).replace('Ta__', '').replace(
                            '~', ' ').replace(' ', '-').strip('{}').lower())
            else:
                tag_list = '/'.join([
                    re.sub('([a-z])([A-Z])', r'\1-\2', t).lower()
                    for t in self.tags.split(',')
                ])
                url = "%(base_dir)s/other/%(tags)s#%(id)s" % dict(
                    base_dir=base_url,
                    tags=tag_list,
                    id=custom_transliteration.tr(
                        self.id, sanscript.IAST).replace('Ta__', '').replace(
                            '~', ' ').replace(' ', '-').strip('{}').lower())

        # Get the description
        description_string = ''
        if hasattr(self, "description"):
            # description_string = json.dumps(self.description)
            description_string += self.description["en"]
            pieces = description_string.split('`')
            if len(pieces) > 1:
                if len(pieces) % 2 == 1:
                    # We much have matching backquotes, the contents of which can be neatly transliterated
                    for i, piece in enumerate(pieces):
                        if (i % 2) == 1:
                            pieces[i] = custom_transliteration.tr(
                                piece, script, False)
                    description_string = ''.join(pieces)
                else:
                    logging.warning(
                        'Unmatched backquotes in description string: %s' %
                        description_string)

        if hasattr(self, "shlokas") and include_shlokas:
            if use_markup:
                description_string = description_string + '\n\n```\n' + custom_transliteration.tr(
                    ", ".join(self.shlokas), script, False) + '\n```'
            else:
                description_string = description_string + '\n\n' + custom_transliteration.tr(
                    ", ".join(self.shlokas), script, False) + '\n\n'

        if include_images:
            if hasattr(self, "image"):
                image_string = '![](https://github.com/sanskrit-coders/adyatithi/blob/master/images/%s)\n\n' % self.image

        if hasattr(self, "references_primary") or hasattr(
                self, "references_secondary"):
            ref_list = '### References\n'
            if hasattr(self, "references_primary"):
                for ref in self.references_primary:
                    ref_list += '* %s\n' % transliterate_quoted_text(
                        ref, sanscript.IAST)
            elif hasattr(self, "references_secondary"):
                for ref in self.references_secondary:
                    ref_list += '* %s\n' % transliterate_quoted_text(
                        ref, sanscript.IAST)

        # Now compose the description string based on the values of
        # include_url, include_images, use_markup, is_brief
        if not is_brief:
            final_description_string = blurb
        else:
            if include_url:
                final_description_string = url
            else:
                final_description_string = ''

        final_description_string += description_string

        if include_images:
            final_description_string += image_string

        if not is_brief and include_url:
            if use_markup:
                final_description_string += (
                    '\n\n[+++](%s)\n' % url) + '\n' + ' '.join(
                        ['#' + x for x in self.tags.split(',')])
            else:
                final_description_string += (
                    '\n\n%s\n' % url) + '\n' + ' '.join(
                        ['#' + x for x in self.tags.split(',')])

        # if use_markup:
        #   final_description_string = final_description_string.replace('\n', '<br/><br/>')

        return final_description_string
Пример #19
0
def write_event_README(event, event_file_name):
    with open(event_file_name) as event_data:
        readme_file_name = os.path.join(os.path.dirname(event_file_name),
                                        'README.md')
        event_dict = json.load(event_data)
        with open(readme_file_name, 'a+') as readme_file:
            readme_file.write('## %s\n' % event_dict["id"].replace(
                'ta__', '').replace('~', ' ').strip('{}'))

            blurb = ''
            month = ''
            angam = ''
            if 'month_type' in event_dict['timing']:
                if event_dict['timing']['month_type'] == 'lunar_month':
                    if event_dict['timing']['month_number'] == 0:
                        month = ' of every lunar month'
                    else:
                        month = ' of ' + get_chandra_masa(
                            event_dict['timing']['month_number'], NAMES,
                            sanscript.IAST) + ' (lunar) month'
                elif event_dict['timing']['month_type'] == 'solar_month':
                    if event_dict['timing']['month_number'] == 0:
                        month = ' of every solar month'
                    else:
                        month = ' of ' + NAMES['RASHI_NAMES'][sanscript.IAST][
                            event_dict['timing']
                            ['month_number']] + ' (solar) month'
            if 'angam_type' in event_dict['timing']:
                logging.debug(event_dict["id"])
                if event_dict["id"][:4] == "ta__":
                    angam = custom_transliteration.tr(
                        event_dict["id"][4:], sanscript.TAMIL).replace(
                            "~", " ").strip("{}") + ' is observed on '
                else:
                    angam = custom_transliteration.tr(
                        event_dict["id"], sanscript.DEVANAGARI).replace(
                            "~", " ") + ' is observed on '

                if event_dict['timing']['angam_type'] == 'tithi':
                    angam += NAMES['TITHI_NAMES'][sanscript.IAST][
                        event_dict['timing']['angam_number']] + ' tithi'
                elif event_dict['timing']['angam_type'] == 'nakshatram':
                    angam += NAMES['NAKSHATRAM_NAMES'][
                        sanscript.IAST][event_dict['timing']
                                        ['angam_number']] + ' nakṣhatram day'
                elif event_dict['timing']['angam_type'] == 'day':
                    angam += 'day %d' % event_dict['timing']['angam_number']
            else:
                logging.debug('No angam_type in %s', event_dict['id'])
            if 'kaala' in event_dict['timing']:
                kaala = event_dict["timing"]["kaala"]
            else:
                kaala = "sunrise (default)"
            if 'priority' in event_dict:
                priority = event_dict["priority"]
            else:
                priority = 'puurvaviddha (default)'
            if angam is not None:
                blurb += angam
            if month is not None:
                blurb += month
            if blurb != '':
                blurb += ' (%s/%s).\n\n' % (kaala, priority)
            readme_file.write(blurb)
            description_string = ""
            logging.debug(event_dict)
            if "description" in event_dict:
                # description_string = json.dumps(event_dict.description)
                # description_string = '_' + event_dict["description"]["en"] + '_'
                description_string = '_' + event.get_description_string(
                    script=sanscript.DEVANAGARI) + '_'
            if "shlokas" in event_dict:
                description_string = description_string + '\n\n```\n' + \
                                     custom_transliteration.tr(", ".join(event_dict["shlokas"]),
                                                               sanscript.DEVANAGARI, False) + '\n```'
            readme_file.write(description_string)
            if "references_primary" in event_dict or "references_secondary" in event_dict:
                readme_file.write('\n')
                readme_file.write('### References\n')
                if "references_primary" in event_dict:
                    for ref in event_dict["references_primary"]:
                        readme_file.write('* %s\n' % ref)
                elif "references_secondary" in event_dict:
                    for ref in event_dict["references_secondary"]:
                        readme_file.write('* %s\n' % ref)
            readme_file.write('\n\n---\n')