Пример #1
0
def tr_single_date(date_, force_date=False):
    if isinstance(date_, datetime.datetime):
        date_ = date_.date()
    today = datetime.datetime.today()
    if date_ == today.date() and not force_date:
        translation = "امروز"
    elif date_ == (today + datetime.timedelta(1)).date() and not force_date:
        translation = "فردا"
    elif date_ == (today - datetime.timedelta(1)).date() and not force_date:
        translation = "دیروز"
    else:
        j = gregorian_to_jalali(date_.year, date_.month, date_.day)
        today_j = gregorian_to_jalali(today.year, today.month, today.day)
        month = tr_jalali_month[j[1]]
        if j[0] == today_j[0]:
            translation = "{} {}".format(num2fa_gen[j[2]], month)
        elif j[0] == today_j[0] + 1:
            translation = "{} {} سال بعد".format(num2fa_gen[j[2]], month)
        elif j[0] == today_j[0] - 1:
            translation = "{} {} پارسال".format(num2fa_gen[j[2]], month)
        else:
            translation = "{} {} سال {}".format(
                num2fa_gen[j[2]], month, j[0] if j[0] >= 1400 else j[0] - 1300)
    return translation
Пример #2
0
    def get_answer(self, question, tokens, labels):
        answer = {
            'type': ['2'],
            'city': [],
            'date': [],
            'time': [],
            'religious_time': [],
            'calendar_type': [],
            'event': [],
            'api_url': [''],
            'result': []
        }
        generated_sentence = ""
        is_wrong_classifier = False
        for k in [
                "سردتر", "گرمتر", "سردترین", "گرمترین", "اختلاف دمای",
                "میانگین دما"
        ]:
            if k in question:
                is_wrong_classifier = True
                break
        if is_wrong_classifier:
            return False
        location = unique_without_sort(
            location_handler(question, tokens, labels))
        answer["city"] = location
        date_list = []
        date_list_jalali = []
        exportdate = export_date(question, tokens, labels)
        events = []
        for d in exportdate:
            if d[0]:
                date_list.append(d[0])
            if (not d[1][0]) and (not d[1][1]) and (type(d[1][2]) != bool):
                events.append(d[1][2])

        answer["event"] = events
        d_n = len(date_list)
        no_date = False
        today = datetime.datetime.today()
        if d_n == 0:
            date_list = [today]
            today_j = gregorian_to_jalali(today.year, today.month, today.day)
            answer["date"] = [format_jalali_date(today_j)]
            d_n = 1
            no_date = True

        date_list = unique_without_sort(date_list)
        d_n = len(date_list)
        date_list_jalali = []
        for d in date_list:
            j = gregorian_to_jalali(d.year, d.month, d.day)
            date_list_jalali.append(format_jalali_date(j))
        answer["date"] = date_list_jalali
        l_n = len(location)
        if l_n == 0:
            answer["city"] = ["تهران"]
            location = ["تهران"]
            l_n = 1
        exportedAdhan = self.export_adhan_names(question)
        n_adhan = len(exportedAdhan)
        if n_adhan == 0:
            return answer, generated_sentence
        answer["religious_time"] = copy(exportedAdhan)
        new_adhan_names = []
        for e in exportedAdhan:
            if tr_adhan_names[e] == "All":
                new_adhan_names.append("اذان صبح")
                new_adhan_names.append("اذان ظهر")
                new_adhan_names.append("اذان مغرب")
                new_adhan_names.append("نیمه شب شرعی")
            else:
                new_adhan_names.append(e)
        exportedAdhan = new_adhan_names
        n_adhan = len(exportedAdhan)
        res, url = self.get_city_adhan_time(location[0], date_list[0].date(),
                                            exportedAdhan[0])
        answer["api_url"] = [url]
        if n_adhan == 1 and l_n == 1 and d_n == 1:
            if res != None:
                answer["result"] = [res.strftime("%H:%M")]
                if date_list[0].date() >= today.date():
                    generated_sentence = "{} به افق {}، {}، {} می‌باشد".format(
                        exportedAdhan[0], location[0],
                        tr_single_date(date_list[0]), tr_single_time(res))
                else:
                    generated_sentence = "{} به افق {}، {}، {} بوده".format(
                        exportedAdhan[0], location[0],
                        tr_single_date(date_list[0]), tr_single_time(res))
            is_hour_lef_asked = False
            ihla = []
            for h in hours_left_asked:
                if h in question:
                    is_hour_lef_asked = True
                    ihla.append(h)
            if not is_hour_lef_asked:
                return answer, cleaning(generated_sentence)
            else:
                tnow = datetime.datetime.now()
                dadhan = datetime.datetime.combine(date_list[0].date(), res)
                if ihla[0] != "گذشته":
                    if dadhan < tnow:
                        dadhan = dadhan + datetime.timedelta(1)
                        date_list[0] = date_list[0] + datetime.timedelta(1)
                    generated_sentence = "تا {} {} {}، {} مانده است"
                else:
                    generated_sentence = "از {} {} {}، {} گذشته است"
                dt = tnow - dadhan if tnow > dadhan else dadhan - tnow
                answer["result"], gd = self.format_time_delta(dt)
                answer["result"] = [answer["result"]]
                generated_sentence = generated_sentence.format(
                    exportedAdhan[0], tr_single_date(date_list[0]),
                    location[0], gd)
        else:
            # check if it's a logical question
            isLogical = False
            for l in adhan_logical_question:
                if l in tokens:
                    isLogical = True
            if isLogical:
                if n_adhan > 1 and l_n == 1 and d_n == 1:
                    answer["result"], answer[
                        "api_url"], gd = self.get_difference_adhan(
                            location[0], location[0], date_list[0],
                            date_list[0], exportedAdhan[0], exportedAdhan[1])
                    generated_sentence = "اختلاف {} و {} {} {}، {} است".format(
                        exportedAdhan[0], exportedAdhan[1],
                        tr_single_date(date_list[0]), location[0], gd)
                elif n_adhan == 1 and l_n > 1 and d_n == 1:
                    answer["result"], answer[
                        "api_url"], gd = self.get_difference_adhan(
                            location[0], location[1], date_list[0],
                            date_list[0], exportedAdhan[0], exportedAdhan[0])
                    generated_sentence = "اختلاف {} {} {}، {} میباشد".format(
                        exportedAdhan[0], tr_single_date(date_list[0]),
                        " و ".join(location), gd)
                elif n_adhan == 1 and l_n == 1 and d_n > 1:
                    answer["result"], answer[
                        "api_url"], gd = self.get_difference_adhan(
                            location[0], location[0], date_list[0],
                            date_list[1], exportedAdhan[0], exportedAdhan[0])
                    generated_sentence = "اختلاف {} {} {}، {} است".format(
                        exportedAdhan[0],
                        " و ".join(tr_date(date_list, tokens,
                                           labels)), location[0], gd)
                elif n_adhan == 2 and l_n == 2 and d_n == 1:
                    answer["result"], answer[
                        "api_url"], gd = self.get_difference_adhan(
                            location[0], location[1], date_list[0],
                            date_list[0], exportedAdhan[0], exportedAdhan[1])
                    generated_sentence = "اختلاف زمان {} {} و {} {} {}، {} میباشد".format(
                        exportedAdhan[0], location[0], exportedAdhan[1],
                        location[1], tr_single_date(date_list[0]), gd)
                elif n_adhan == 2 and l_n == 1 and d_n == 2:
                    answer["result"], answer[
                        "api_url"], gd = self.get_difference_adhan(
                            location[0], location[0], date_list[0],
                            date_list[1], exportedAdhan[0], exportedAdhan[1])
                    generated_sentence = "اختلاف زمان {} {} و {} {} {}، {} میباشید".format(
                        exportedAdhan[0],
                        tr_single_date(date_list[0]), exportedAdhan[1],
                        tr_single_date(date_list[1]), location[0], gd)
                elif n_adhan == 1 and l_n == 2 and d_n == 2:
                    answer["result"], answer[
                        "api_url"], gd = self.get_difference_adhan(
                            location[0], location[1], date_list[0],
                            date_list[0], exportedAdhan[0], exportedAdhan[1])
                    generated_sentence = "اختلاف زمان {} {} {} و {} {}، {} است".format(
                        exportedAdhan[0],
                        tr_single_date(date_list[0]), location[0],
                        tr_single_date(date_list[1]), location[1], gd)
            else:
                res_list = []
                url_list = []
                if n_adhan >= 2 and l_n == 1 and d_n == 1:
                    generated_sentence = "{} به افق {} ".format(
                        tr_single_date(date_list[0]), location[0])
                    for i, ad in enumerate(exportedAdhan):
                        res, url = self.get_city_adhan_time(
                            location[0], date_list[0].date(), ad)
                        if res != None and url != None:
                            res_list.append(res.strftime("%H:%M"))
                            url_list.append(url)
                            if i < n_adhan - 2:
                                generated_sentence = generated_sentence + \
                                    "{} ،{} ، ".format(ad, tr_single_time(res))
                            elif i == n_adhan - 2:
                                generated_sentence = generated_sentence + \
                                    "{} ،{} و ".format(ad, tr_single_time(res))
                            else:
                                generated_sentence = generated_sentence + \
                                    "{} ،{} ".format(ad, tr_single_time(res))
                    if date_list[0].date() >= today.date():
                        generated_sentence = generated_sentence + "میباشد"
                    else:
                        generated_sentence = generated_sentence + "بوده"
                elif n_adhan == 1 and l_n >= 2 and d_n == 1:
                    generated_sentence = "{} ".format(
                        tr_single_date(date_list[0]))
                    for i, lc in enumerate(location):
                        res, url = self.get_city_adhan_time(
                            lc, date_list[0].date(), exportedAdhan[0])
                        if res != None and url != None:
                            res_list.append(res.strftime("%H:%M"))
                            url_list.append(url)
                            if i < l_n - 2:
                                generated_sentence = generated_sentence + \
                                    "{} به افق {}، {} ،".format(
                                        exportedAdhan[0], lc, tr_single_time(res))
                            elif i == l_n - 2:
                                generated_sentence = generated_sentence + \
                                    "{} به افق {}، {} و ".format(
                                        exportedAdhan[0], lc, tr_single_time(res))
                            else:
                                generated_sentence = generated_sentence + \
                                    "{} به افق {}، {} ".format(
                                        exportedAdhan[0], lc, tr_single_time(res))
                    generated_sentence = generated_sentence + " میباشد"
                elif n_adhan == 1 and l_n == 1 and d_n >= 2:
                    generated_sentence = "{} {}، ".format(
                        exportedAdhan[0], location[0])

                    for i, dat in enumerate(date_list):
                        res, url = self.get_city_adhan_time(
                            location[0], dat.date(), exportedAdhan[0])
                        if res != None and url != None:
                            res_list.append(res.strftime("%H:%M"))
                            url_list.append(url)
                            if i < d_n - 2:
                                generated_sentence = generated_sentence + \
                                    "{}، {}، ".format(tr_single_date(
                                        dat), tr_single_time(res))
                            elif i == d_n - 2:
                                generated_sentence = generated_sentence + \
                                    "{}، {} و ".format(tr_single_date(
                                        dat), tr_single_time(res))
                            else:
                                generated_sentence = generated_sentence + \
                                    "{}، {}، ".format(tr_single_date(
                                        dat), tr_single_time(res))
                    generated_sentence = generated_sentence + " میباشد"

                elif n_adhan == l_n and d_n == 1:
                    generated_sentence = "{}، ".format(
                        tr_single_date(date_list[0]))
                    s = 0
                    for ad, lc in zip(exportedAdhan, location):
                        res, url = self.get_city_adhan_time(
                            lc, date_list[0].date(), ad)
                        if res != None and url != None:
                            res_list.append(res.strftime("%H:%M"))
                            url_list.append(url)
                            if s < l_n - 2:
                                generated_sentence = generated_sentence + \
                                    "{} {}، {}، ".format(
                                        ad, lc, tr_single_time(res))
                            elif s == l_n - 2:
                                generated_sentence = generated_sentence + \
                                    "{} {}، {} و ".format(
                                        ad, lc, tr_single_time(res))
                            else:
                                generated_sentence = generated_sentence + \
                                    "{} {}، {} ".format(
                                        ad, lc, tr_single_time(res))
                            s += 1
                    generated_sentence = generated_sentence + "میباشد"
                elif n_adhan == 1 and l_n == d_n:
                    generated_sentence = ""
                    s = 0
                    for lc, dat in zip(location, date_list):
                        res, url = self.get_city_adhan_time(
                            lc, dat.date(), exportedAdhan[0])
                        if res != None and url != None:
                            res_list.append(res.strftime("%H:%M"))
                            url_list.append(url)
                            if s < l_n - 2:
                                generated_sentence = generated_sentence + \
                                    "{} {}، {}، {}، ".format(
                                        exportedAdhan[0], lc, tr_single_date(dat), tr_single_time(res))
                            elif s == l_n - 2:
                                generated_sentence = generated_sentence + \
                                    "{} {}، {}، {} و ".format(
                                        exportedAdhan[0], lc, tr_single_date(dat), tr_single_time(res))
                            else:
                                generated_sentence = generated_sentence + \
                                    "{} {}، {}، {} ".format(
                                        exportedAdhan[0], lc, tr_single_date(dat), tr_single_time(res))
                            s += 1
                    generated_sentence = generated_sentence + "میباشد"

                elif n_adhan == d_n and l_n == 1:
                    generated_sentence = ""
                    s = 0
                    for ad, dat in zip(exportedAdhan, date_list):
                        res, url = self.get_city_adhan_time(
                            location[0], dat.date(), ad)
                        if res != None and url != None:
                            res_list.append(res.strftime("%H:%M"))
                            url_list.append(url)
                            if s < d_n - 2:
                                generated_sentence = generated_sentence + \
                                    "{} {}، {}، ".format(
                                        tr_single_date(dat), ad, tr_single_time(res))
                            elif s == d_n - 2:
                                generated_sentence = generated_sentence + \
                                    "{} {}، {} و ".format(
                                        tr_single_date(dat), ad, tr_single_time(res))
                            else:
                                generated_sentence = generated_sentence + \
                                    "{} {}، {} ".format(
                                        tr_single_date(dat), ad, tr_single_time(res))
                            s += 1

                    generated_sentence = generated_sentence + \
                        "به افق {} میباشد".format(location[0])

                elif (n_adhan == d_n) and (l_n == d_n):
                    generated_sentence = ""
                    s = 0
                    for i in range(d_n):
                        res, url = self.get_city_adhan_time(
                            location[i], date_list[i].date(), exportedAdhan[i])
                        if res != None and url != None:
                            res_list.append(res.strftime("%H:%M"))
                            url_list.append(url)
                            if s < l_n - 2:
                                generated_sentence = generated_sentence + \
                                    "{}، {} {}، {}، ".format(tr_single_date(
                                        date_list[i]), exportedAdhan[i], location[i], tr_single_time(res))
                            elif s == l_n - 2:
                                generated_sentence = generated_sentence + \
                                    "{} {}، {}، {} و ".format(tr_single_date(
                                        date_list[i]), exportedAdhan[i], location[i], tr_single_time(res))
                            else:
                                generated_sentence = generated_sentence + \
                                    "{} {}، {} {} ".format(tr_single_date(
                                        date_list[i]), exportedAdhan[i], location[i], tr_single_time(res))
                            s += 1
                    generated_sentence = generated_sentence + "میباشد"

                answer["result"] = res_list
                answer["api_url"] = url_list
                return answer, cleaning(generated_sentence)

        return answer, cleaning(generated_sentence)
Пример #3
0
    def get_single_answer(self, question, answer, date_list, events, bii=None):
        today = datetime.datetime.today()
        is_weeks_day_asked = False
        generated_sentence = ""
        for w in week_days_asked:
            if w in question:
                is_weeks_day_asked = True
        if is_weeks_day_asked:
            wd = date_list[0].weekday()
            result = week_days[tr_isoweek_toperweekday(wd)]
            answer["result"].append(result)
            if not events:
                if date_list[0].date() >= today.date():
                    generated_sentence = "{}، {} است".format(
                        tr_single_date(date_list[0]), result)
                else:
                    generated_sentence = "{}، {} بوده".format(
                        tr_single_date(date_list[0]), result)
            else:
                if date_list[0].date() >= today.date():
                    generated_sentence = "{}، مصادف با {}، {} است".format(
                        " ".join(events), tr_single_date(date_list[0]), result)
                else:
                    generated_sentence = "{}، مصادف با {}، {} بوده".format(
                        " ".join(events), tr_single_date(date_list[0]), result)

            return answer, generated_sentence

        # check if converting date is asked:
        convert_list = []
        for k in convert_asked.keys():
            if k in question:
                convert_list.append(k)
        if convert_list:
            a = convert_asked[convert_list[0]]
            if a == 0:
                res = answer["date"][0]
                answer["calendar_type"].append("شمسی")
                generated_sentence = "تاریخ داده شده به شمسی، {} میباشد".format(
                    tr_single_date(date_list[0]))
            elif a == 1:
                res = date_list[0].strftime("%Y-%m-%d")
                answer["calendar_type"].append("میلادی")
                generated_sentence = "تاریخ داده شده به میلادی، {} میباشد".format(
                    tr_gregorian_date(date_list[0]))
            else:
                new_date = date_list[0] - datetime.timedelta(1)
                res = convert.Gregorian(new_date.year, new_date.month,
                                        new_date.day).to_hijri()

                res = format_jalali_date([res.year, res.month, res.day])
                answer["calendar_type"].append("قمری")
                generated_sentence = "تاریخ داده شده به قمری، {} میباشد".format(
                    tr_hijri_date(date_list[0]))
            answer["result"].append(res)
            return answer, generated_sentence

        # check if events is asked
        if not events:
            is_event_asked = False
            for ea in event_asked:
                if ea in question:
                    is_event_asked = True
            if is_event_asked:
                d_j = gregorian_to_jalali(date_list[0].year,
                                          date_list[0].month, date_list[0].day)
                d_str = "({}, {}, {})".format(d_j[0], d_j[1], d_j[2])
                f_event = df_event["event"].loc[df_event["j_d"] ==
                                                d_str].to_numpy()
                if not len(f_event) == 0:
                    res = []
                    for e in f_event:
                        res.append(
                            e.replace(" و ",
                                      "-").replace("؛", "-").replace("،", "-"))
                    res = np.unique(res)
                    answer["result"].append("-".join(res))
                    generated_sentence = "{} {} است".format(
                        tr_single_date(date_list[0]), " و ".join(res))
                else:
                    answer["result"].append("مناسبتی وجود ندارد")
                    generated_sentence = "{} مناسبتی وجود ندارد".format(
                        tr_single_date(date_list[0]))
                return answer, generated_sentence
        if events:
            j = gregorian_to_jalali(date_list[0].year, date_list[0].month,
                                    date_list[0].day)
            answer["result"].append(format_jalali_date(j))
            generated_sentence = "{}، مصادف با {} میباشد".format(
                " ".join(events), tr_single_date(date_list[0]))
            return answer, generated_sentence
        if bii:
            j = gregorian_to_jalali(date_list[0].year, date_list[0].month,
                                    date_list[0].day)
            answer["result"].append(format_jalali_date(j))
            generated_sentence = "{}، {} است".format(
                bii, tr_single_date(date_list[0], True))
            return answer, generated_sentence
        return None, generated_sentence
Пример #4
0
    def get_answer(self, question, tokens, labels):
        answer = {
            'type': ['4'],
            'city': [],
            'date': [],
            'time': [],
            'religious_time': [],
            'calendar_type': [],
            'event': [],
            'api_url': [''],
            'result': []
        }
        generated_sentence = ""
        is_time_asked = False
        for t in time_asked:
            if t in question:
                is_time_asked = True

        if is_time_asked:
            return self.time.get_answer(question, tokens, labels)

        date_list = []
        date_list_jalali = []
        exportdate = export_date(question, tokens, labels, True)
        events = []
        which_date_is_event = []
        for i, d in enumerate(exportdate):
            if d[0]:
                date_list.append(d[0])
            if (not d[1][0]) and (not d[1][1]) and (type(d[1][2]) != bool):
                events.append(d[1][2])
                which_date_is_event.append(i)

        d_n = len(date_list)
        today = datetime.datetime.today()
        no_date = False
        if d_n == 0:
            date_list = [today]
            d_n = 1
            no_date = True
        date_list = unique_without_sort(date_list)
        d_n = len(date_list)
        date_list_jalali = []
        for d in date_list:
            j = gregorian_to_jalali(d.year, d.month, d.day)
            date_list_jalali.append(format_jalali_date(j))

        answer["date"] = date_list_jalali
        event_list = events
        answer["event"] = list(event_list)
        self.bii = concatenate_bi(tokens, labels, "B_DAT", "I_DAT")

        if no_date:
            answer["result"] = date_list_jalali
            generated_sentence = "امروز، {} است".format(
                tr_single_date(date_list[0], force_date=True))
        else:
            if d_n == 1:
                asingle, generated_sentence = self.get_single_answer(
                    question, answer, date_list, events)
                if asingle != None:
                    answer = asingle
                else:
                    answer["result"] = date_list_jalali
                    trsd = tr_single_date(date_list[0], True)
                    if self.bii:
                        if date_list[0].date() >= today.date():
                            generated_sentence = "{}، {} میباشد".format(
                                " ".join(self.bii), trsd)
                        else:
                            generated_sentence = "{}، {} بوده است".format(
                                " ".join(self.bii), trsd)
                    else:
                        if date_list[0].date() >= today.date():
                            generated_sentence = "تاریخ داده شده {} است".format(
                                trsd)
                        else:
                            generated_sentence = "تاریخ داده شده {} بوده".format(
                                trsd)
            else:
                answer["result"] = []
                tokenize_questions = hazm.sent_tokenize(question)
                if len(tokenize_questions) == 1:
                    tokenize_questions = question.split(" و ")
                if d_n == len(tokenize_questions):
                    generated_sentence = ""
                    if d_n != len(events):
                        s = 0
                        for i, (d, tk) in enumerate(
                                zip(date_list, tokenize_questions)):
                            if i in which_date_is_event:
                                n_answer, n_generated_sentence = self.get_single_answer(
                                    tk, answer, [d],
                                    [events[which_date_is_event[s]]],
                                    self.bii[i]
                                    if len(self.bii) == d_n else None)
                                s += 1
                            else:
                                n_answer, n_generated_sentence = self.get_single_answer(
                                    tk, answer, [d], None, self.bii[i]
                                    if len(self.bii) == d_n else None)
                            if n_answer != None:
                                answer = n_answer
                                if generated_sentence:
                                    generated_sentence = generated_sentence + " و " + n_generated_sentence
                                else:
                                    generated_sentence = n_generated_sentence
                            else:
                                n_answer, n_generated_sentence = self.get_single_answer(
                                    question, answer, [d], events, self.bii[i]
                                    if len(self.bii) == d_n else None)
                                if n_answer != None:
                                    answer = n_answer
                                    if generated_sentence:
                                        generated_sentence = generated_sentence + " و " + n_generated_sentence
                                    else:
                                        generated_sentence = n_generated_sentence
                                else:
                                    n_generated_sentence = "تاریخ داده شده {} میباشد".format(
                                        tr_single_date(d))

                                    j = gregorian_to_jalali(
                                        d.year, d.month, d.day)
                                    answer["result"].append(
                                        format_jalali_date(j))
                                    if generated_sentence:
                                        generated_sentence = generated_sentence + " و " + n_generated_sentence
                                    else:
                                        generated_sentence = n_generated_sentence
                    else:
                        for i in range(d_n):
                            n_answer, n_generated_sentence = self.get_single_answer(
                                tokenize_questions[i], answer, [date_list[i]],
                                [events[i]],
                                self.bii[i] if len(self.bii) == d_n else None)
                            if n_answer != None:
                                answer = n_answer
                                if generated_sentence:
                                    generated_sentence = generated_sentence + " و " + n_generated_sentence
                                else:
                                    generated_sentence = n_generated_sentence
                            else:
                                n_answer, n_generated_sentence = self.get_single_answer(
                                    question, answer, [date_list[i]],
                                    [events[i]], self.bii[i]
                                    if len(self.bii) == d_n else None)
                                if n_answer != None:
                                    answer = n_answer
                                    if generated_sentence:
                                        generated_sentence = generated_sentence + " و " + n_generated_sentence
                                    else:
                                        generated_sentence = n_generated_sentence
                                else:
                                    j = gregorian_to_jalali(
                                        date_list[i].year, date_list[i].month,
                                        date_list[i].day)
                                    answer["result"].append(
                                        format_jalali_date(j))
                                    n_generated_sentence = "تاریخ داده شده {} است".format(
                                        tr_single_date(date_list[i]))
                                    if generated_sentence:
                                        generated_sentence = generated_sentence + " و " + n_generated_sentence
                                    else:
                                        generated_sentence = n_generated_sentence

                else:
                    for d in date_list:
                        n_answer, n_generated_sentence = self.get_single_answer(
                            question, answer, [d], events,
                            self.bii[i] if len(self.bii) == d_n else None)
                        if n_answer != None:
                            answer = n_answer
                            if generated_sentence:
                                generated_sentence = generated_sentence + " و " + n_generated_sentence
                            else:
                                generated_sentence = n_generated_sentence
        return answer, cleaning(generated_sentence)
Пример #5
0
    def get_answer(self, question, tokens, labels):
        answer = {
            'type': ['3'],
            'city': [],
            'date': [],
            'time': [],
            'religious_time': [],
            'calendar_type': [],
            'event': [],
            'api_url': [''],
            'result': []
        }

        generated_sentence = ""
        date = datetime.datetime.today().date()
        exportd = export_date(question, tokens, labels)
        no_date = True
        if exportd[0][0] != None:
            date = exportd[0][0].date()
            answer["date"] = [
                format_jalali_date(
                    gregorian_to_jalali(date.year, date.month, date.day))
            ]
            no_date = False

        time_list = []
        time_iso = []
        exporttime, is_adhan, adhan_url, adhan_names = export_time(
            question, tokens, labels)
        if is_adhan:
            answer["religious_time"] = adhan_names
            answer["api_url"].append(adhan_url)

        for t in exporttime:
            if t != None:
                time_list.append(t.strftime("%H:%M"))
                time_iso.append(datetime.datetime.combine(date, t))
        t_n = len(time_iso)
        no_time = False
        if t_n == 0:
            now = datetime.datetime.now()
            time_list.append(now.strftime("%H:%M"))
            time_iso.append(datetime.datetime.combine(date, now.time()))
            t_n = 1
            no_time = True

        answer["time"] = time_list
        location = list(
            unique_without_sort(location_handler(question, tokens, labels)))
        if len(location) == 1 and location[0] == USER_CITY:
            location = []
        answer["city"] = location
        if len(location) == 0:
            answer["result"].append(time_list[0])
            if no_time:
                generated_sentence = "الآن {} است".format(
                    tr_single_time(time_iso[0]))
            else:
                generated_sentence = "{} میباشد".format(
                    tr_single_time(time_iso[0]))
            is_hour_lef_asked = False
            for h in hours_left_asked:
                if h in question:
                    is_hour_lef_asked = True
            if is_hour_lef_asked:
                tnow = datetime.datetime.now()
                dt = abs(tnow - time_iso[0])
                r, gt = self.format_time_delta(dt)
                answer["result"] = [r]
                if no_date:
                    if time_iso[0] > tnow:
                        generated_sentence = "تا {}، {} مانده است".format(
                            tr_single_time(time_iso[0]), gt)
                    else:
                        generated_sentence = "از {}، {} گذشته است".format(
                            tr_single_time(time_iso[0]), gt)
                else:
                    if time_iso[0] > tnow:
                        generated_sentence = "تا {} {}، {} مانده است".format(
                            tr_single_time(time_iso[0]), tr_single_date(date),
                            gt)
                    else:
                        generated_sentence = "از {} {}، {} گذشته است".format(
                            tr_single_time(time_iso[0]), tr_single_date(date),
                            gt)

            return answer, cleaning(generated_sentence)

        location_country = []
        for l in location:
            c = self.countries_df["summary"].iloc[np.where(
                self.countries_df["title"] == l)].to_numpy()
            if len(c) > 0:
                location_country.append(c[0][:-1])

        time_zone_list = []
        if len(location) > len(location_country):
            for l in location:
                if l in location_country:
                    continue
                city_info = Weather.get_city_info(l)
                if city_info == None:
                    s = re.sub("^ا", "آ", l)
                    city_info = Weather.get_city_info(s)
                if city_info != None:
                    p_tz = self.possible_timezones(city_info["timezone"])
                    if not p_tz:
                        p_tz = self.possible_timezones(city_info["timezone"],
                                                       False)
                    if p_tz:
                        time_zone_list.append(p_tz[0])

        if location_country:
            location_country = list(unique_without_sort(location_country))
            for l in location_country:
                tz = self.zone_df["Europe/Andorra"].iloc[np.where(
                    self.zone_df["AD"] == l)].to_numpy()
                if len(tz) >= 1:
                    time_zone_list.append(tz[0])

        is_reversed_asked = False
        for r in time_reverse_convert:
            if r in question:
                is_reversed_asked = True

        if len(time_zone_list) == 1:
            new_location = copy(location)
            single_ans, generated_sentence = self.get_single_answer(
                question, [location[-1]], time_zone_list, time_iso)
            answer["result"] = single_ans if isinstance(
                single_ans, list) else [single_ans]
        elif len(time_zone_list) == 2 and is_reversed_asked:
            time_zone_list.remove("Asia/Tehran")
            timzon = pytz.timezone(time_zone_list[0])
            t = timzon.localize(time_iso[0], is_dst=None).astimezone(pytz.utc)
            t = t.astimezone(self.local_time)
            answer["result"] = [t.strftime("%H:%M")]
            new_location = copy(location)
            try:
                new_location.remove("تهران")
            except Exception:
                try:
                    new_location.remove("ایران")
                except Exception:
                    pass

            generated_sentence = "{} در {}، {} به وقتa تهران میباشد".format(
                tr_single_time(time_iso[0], literal=False), new_location[0],
                tr_single_time(t, literal=False))
        else:
            time_list = []
            for tz in time_zone_list:
                time_zone = pytz.timezone(tz)
                t = self.local_time.localize(time_iso[0],
                                             is_dst=None).astimezone(pytz.utc)
                t = t.astimezone(time_zone)
                d = datetime.datetime(t.year, t.month, t.day, t.hour, t.minute)
                time_list.append(d)
            is_hours_difference_asked = False
            for h in hours_difference_asked:
                if h in question:
                    is_hours_difference_asked = True

            if is_hours_difference_asked:
                dt = abs(time_list[0] - time_list[-1])
                r, gt = self.format_time_delta(dt)
                generated_sentence = "اختلاف زمان {} و {}، {} است".format(
                    location[0], location[-1], gt)
                answer["result"] = [r]
            else:

                new_location = copy(location)
                if (len(time_zone_list) == 2
                        and "Asia/Tehran" in time_zone_list):
                    time_zone_list.remove("Asia/Tehran")
                    new_location.remove(USER_CITY)
                location = new_location
                t_s = []
                for t in time_list:
                    t_s.append(t.strftime("%H:%M"))
                if not len(t_s) == len(location):
                    t_s = unique_without_sort(t_s)
                l_n = len(location)
                if l_n == len(t_s):
                    generated_sentence = "{} ".format(
                        tr_single_time(time_iso[0], True))
                    for i, (t, lc) in enumerate(zip(time_list, location)):
                        if i != l_n - 1:
                            generated_sentence = generated_sentence + "در {}، {} و ".format(
                                lc, tr_single_time(t, True))
                        else:
                            generated_sentence = generated_sentence + "در {}، {} ".format(
                                lc, tr_single_time(t, True))

                    generated_sentence = generated_sentence + "میباشد"
                answer["result"] = t_s
        return answer, cleaning(generated_sentence)