Esempio n. 1
0
def temperature(wInfo, period, lang):
    temperature_terms = wInfo.get_temperature(period)
    if temperature_terms == None: return None
    maxTemp = get_max_term(temperature_terms, 0).infos[0]
    minTemp = get_min_term(temperature_terms, 0).infos[0]
    dn = "night" if period in ["tonight", "tomorrow_night"] else "day"
    tempVals = wInfo.get_temperature_values(period)
    periodName = periodNames[period][lang](wInfo.get_issue_date())
    # checking for an abnormal temperature trend, either
    #     positive change of least 3°C during the night
    #     negative change of last 3°C during the day
    (t1,t2,i1)=(maxTemp,minTemp,tempVals.index(minTemp)) if dn=="night" else\
               (minTemp,maxTemp,tempVals.index(maxTemp))
    # print("dn=",dn,"t1=",t1,"t2=",t2)
    if t1 >= t2 + 3:  # abnormal change time
        if i1 <= 1:
            return realize(jsrAbnormal[dn]["a"][lang](t1, periodName), lang,
                           False)
        else:
            if i1 < 6:  # abnormality occurs during the first 6 hours of the period
                rest = tempVals[i1:]
                if all([abs(t - t1) <= 2 for t in rest]):
                    # c) remains +/- 2 for the rest of the period
                    return realize(jsrAbnormal[dn]["c"][lang](t1, periodName),
                                   lang, False)
                elif any([t - t1 > 2 for t in rest]):
                    # d) rises more than 2 for the rest
                    return realize(jsrAbnormal[dn]["d"][lang](t1, periodName),
                                   lang, False)
                elif any([t1 - t > 2 for t in rest]):
                    # e) falls more than 2 for the rest (this should never happen!!!)
                    return realize(jsrAbnormal[dn]["e"][lang](t1, periodName),
                                   lang, False)
            else:
                # b) low temperature after the beginning (but no special case)

                return realize(
                    jsrAbnormal[dn]["b"][lang](t1, jsrTemp(t2, lang)), lang,
                    False)
    # normal case
    res = []
    if lang == "en":  # output maximum temperature
        res.append(realize(S(Adv("high"), jsrTemp(maxTemp, "en")), "en",
                           False))
    else:
        res.append(
            realize(S(N("maximum"), jsrTemp(maxTemp, "fr")), "fr", False))
    if minTemp < maxTemp - 2:  # output minimum if it differs significantly from the maximum
        if lang == "en":
            res.append(
                realize(S(Adv("low"), jsrTemp(minTemp, "en")), "en", False))
        else:
            res.append(
                realize(S(N("minimum"), jsrTemp(minTemp, "fr")), "fr", False))
    return " ".join(res)
Esempio n. 2
0
def jsrHour(h,lang):
    if h in range(0,6):
        return PP(P("during"),NP(D("the"),N("night"))) if lang=="en" else \
               PP(P("durant"),NP(D("le"),N("nuit")))
    if h in range(6,11):
        return PP(P("in"),NP(D("the"),N("morning"))) if lang=="en" else \
               NP(D("le"),N("matin"))
    if h in range(11,14):
        return PP(P("around"),N("noon")) if lang=="en" else \
               PP(P("vers"),N("midi"))
    if h in range(14,18):
        return PP(P("in"),NP(D("the"),N("afternoon"))) if lang=="en"  else \
               PP(P("durant"),NP(D("le"),N("après-midi")))
    if h in range(18,24):
        return PP(P("in"),NP(D("the"),N("evening"))) if lang=="en"  else \
               PP(P("dans"),NP(D("le"),N("soirée"))) 
Esempio n. 3
0
def title_block(wInfo, lang):
    issueDate = wInfo.get_issue_date()
    noSecond = {"second": False}
    if lang == "en":
        s1 = S(
            NP(N("forecast").n("p")),
            VP(
                V("issue").t("pp"),
                PP(
                    P("by"), Q("jsRealB"),
                    DT(issueDate).dOpt(noSecond), P("for"),
                    CP(
                        C("and"), N("today"),
                        DT(issueDate + datetime.timedelta(days=1)).dOpt(
                            {"rtime": issueDate})))))
        s2 = S(
            NP(D("the"), D("next"),
               V("schedule").t("pp"),
               N("forecast").n("p")),
            VP(
                V("be").t("f"),
                V("issue").t("pp"),
                DT(wInfo.get_next_issue_date()).dOpt(noSecond)))
    else:
        s1 = S(
            NP(N("prévision").n("p")),
            VP(
                V("émettre").t("pp"),
                PP(
                    P("par"), Q("jsRealB"),
                    DT(issueDate).dOpt(noSecond), P("pour"),
                    CP(
                        C("et"), Adv("aujourd'hui"),
                        DT(issueDate + datetime.timedelta(days=1)).dOpt(
                            {"rtime": issueDate})))))
        s2 = S(
            NP(D("le"),
               A("prochain").pos("pre"),
               N("prévision").n("p")),
            VP(
                V("être").t("f"),
                V("émettre").t("pp"),
                DT(wInfo.get_next_issue_date()).dOpt(noSecond)))
    return "\n".join([realize(s1, lang, False), realize(s2, lang, False)])
Esempio n. 4
0
def jsrDayPeriod(hour,lang):
    isTomorrow=hour>23
    hour=hour%24
    for (s,e,jsrExp) in dayPeriods:
        if hour in range(s,e):
            exp=jsrExp[lang]()
            if isTomorrow:
                return exp.add(N("tomorrow" if lang=="en" else "demain"),0)
            elif s!=18:
                return exp.add(D("this" if lang=="en" else "ce"),0)
Esempio n. 5
0
def precipitation(wInfo,period,lang):
    jsrExprs=[]
    prob_terms=wInfo.get_precipitation_probabilities(period)
    type_terms=wInfo.get_precipitation_type(period)
    accum_terms=wInfo.get_precipitation_accumulation(period)
    for prob_term in prob_terms:
        prob_val=round(prob_term.infos[0]/10)*10
        type_term=get_term_at(type_terms,prob_term.start)
        if type_term!=None and prob_val>=30:     # interesting precipitation
            if prob_val <= 70 and prob_val!=50:  # show probability
                if lang=="en":
                    prob=NP(NO(prob_val),Q("percent"),N("chance").n("s"),P("of"))
                else:
                    prob=NP(NO(prob_val),Q("pour cent"),P("de"),N("probabilité").n("s"),P("de"))
                timePeriod=None
            else:                                # probability >= 80% 
                prob=None                        # indicate beginning or ending
                start=prob_term.start
                end=prob_term.end
                if wInfo.is_in_period(start,period):  
                    timePeriod=VP(V("begin" if lang=="en" else "débuter").t("pr"),jsrHour(start%24,lang))
                elif wInfo.is_in_period(end,period):
                    timePeriod=VP(V("end" if lang=="en" else "finir").t("pr"),jsrHour(end%24,lang))
                else:
                    timePeriod=None
            jsrExpr=NP(prob,precipitationTypes[type_term.infos[0]][lang],timePeriod)            
            amount_term=get_term_at(accum_terms,prob_term.start)
            if amount_term!=None:                 # check for significant amount
                pcpnType=amount_term.infos[0]
                amount=amount_term.infos[1]
                jsrAmount=None
                if pcpnType=="rain" and amount>=25:
                    jsrAmount=NP(NO(round(amount)),Q("mm"))
                elif pcpnType=="snow" and amount>=2:
                    jsrAmount=NP(NO(round(amount)),Q("cm"))
                if jsrAmount!=None:
                    if lang=="en":
                        jsrAmount.add(N("amount"),0)
                    else:
                        jsrAmount.add(N("accumulation"),0).add(P("de"),1)
                    jsrExpr=SP(jsrExpr.a(","),jsrAmount)   
            jsrExprs.append(jsrExpr)
    return " ".join(realize(jsrExpr,lang) for jsrExpr in jsrExprs)
Esempio n. 6
0
def frequencyRole(semR, env, opts):
    traceSyntR("frequencyRole", semR)
    concept = semR.get_concept()
    instance = semR.get_instance()
    if concept == None and is_number(instance):
        if instance == 1:
            env.push(Adv("once"))
        elif instance == 2:
            env.push(D("twice"))
        else:
            env.push(NP(NO(instance), N("time")))
    else:
        env.push(makeSyntR(semR))
Esempio n. 7
0
def quantity(concept,roles,env,opts):
    traceSyntR("quantity",concept)
    if ":quant" in roles:
        qty=makeSyntR(roles[":quant"])
        if ":unit" in roles:
            unit=makeSyntR(roles[":unit"])
            if isinstance(unit,Pro): # get the referenced unit...
                unit=makeSyntR(roles[":unit"].instance)
            if isinstance(unit,NP) and qty!=None and isinstance(qty,NO):
                unit.elements[0]=qty
                qty=unit
            elif isinstance(unit,Phrase):
                qty=unit.add(qty)
            else:
                qty=SP(unit,qty)
        elif len(roles)>1 and isinstance(qty,Terminal):
            qty=NP(qty)
        if ":scale" in roles:
            qty.add(PP(P("on"),makeSyntR(roles[":scale"]),N("scale")))
        if ":*:ARG1" in roles:
            qty.add([D("the"),N("quantity"),Pro("that")])
        env.push(qty)
    return addRoles(concept,roles,[":quant",":unit",":scale"],LexSem("qty","SP",[],lambda:SP()),env,opts)
Esempio n. 8
0
def paperExample():
    from jsRealBclass import jsRealB, N,A,Adv,V,D,P,C,DT,NO,Q, NP,AP,AdvP,VP,S,SP,PP,CP
    ##  example function used in the paper
    def pcpn(type,action,tense,moment,quantity=None,unit=None):
    	return S(type,
    	         VP(V(action).t(tense),
    			    CP(PP(P("in"),NP(D("the"),N(moment))),
    				   None if quantity==None else NP(N("amount"),NP(NO(quantity),unit)))))
    
    print(realize(pcpn(N("flurry").n("p"),"begin","p","morning",2,N("foot")),"en"))
    print(realize(pcpn(N("rain"),"begin","p","evening",1,N("inch")),"en"))
    print(realize(pcpn(N("snow"),"stop","pr","evening"),"en"))
    print(realize(pcpn(NP(V("freeze").t("pr"),N("drizzle")),"start","f","morning"),"en"))
Esempio n. 9
0
def hyperlink91(concept,roles,env,opts):
    traceSyntR("hyperlink91",concept)
    if ":ARG1" in roles:
        text=makeSyntR(roles[":ARG1"])
    else:
        text=NP(N("link"))
    if roles.areEmpty():
        return text.tag(("a",{"href":"#"}))
    if ":ARG3" in roles:
        if roles[":ARG3"].instanceIsRef():
            return text.tag(("a",{"href":"#"}))
        if roles[":ARG3"].concept=="url-entity":
            urlEntity=roles[":ARG3"]
            if ":value" in urlEntity.roles:
                link=urlEntity.roles[":value"].get_instance()
            elif urlEntity.roles.areEmpty():
                link="#"
            opts.add("tag",("a",{"href":link}))
            return addRoles(concept,roles,[":ARG1",":ARG3"],LexSem("hyperlink","NP",[],lambda:text),env,opts)
    return None
Esempio n. 10
0
def haveQuant91(concept,roles,env,opts):
    traceSyntR("haveQuant91",concept)
    if ":ARG1" in roles:
        quant=makeSyntR(roles[":ARG1"])
    else:
        errorSyntR("haveQuant91 without entity:%s"%concept)
        quant=SP(Q("*entity*"))
    if isinstance(quant,Terminal):
        quant=SP(quant)
    if ":ARG2" in roles:
        quant.add(makeSyntR(roles[":ARG2"]),0)
    else:
        quant.add(NP(D("the"),N("number"),P("of")),0)
    if ":ARG3" in roles:
        quant.add(VP(V("be"),makeSyntR(roles[":ARG3"])))        
    if ":ARG4" in roles:
        quant.add(PP(P("than"),
                        makeSyntR(roles[":ARG4"])))
    if ":ARG5" in roles:
        quant.add(PP(P("of"),makeSyntR(roles[":ARG5"])))
    if ":ARG6" in roles:
        quant.add(PP(P("for"),makeSyntR(roles[":ARG6"])))
    return addRoles(concept, roles, [":ARG1",":ARG2",":ARG3",":ARG4",":ARG5",":ARG6"], 
                    LexSem("qty","NP",[],lambda:quant), env, opts)
Esempio n. 11
0
 def simpleModNoun(concept, neg):  ## check for "simple" cases
     if concept in [
             "all", "many", "both", "no", "too", "any", "other", "some",
             "one", "kind-yy", "then", "such"
     ]:
         env.put(":D", Q("kind of" if concept == "kind-yy" else concept))
         if neg: env.unshift(Q("not"))
         if concept in ["all", "many", "both"]:
             opts.add("n", "p")
     elif concept in determiners:
         env.put(":D", D(concept))
     elif is_number(concept):
         env.push(NO(concept))
     elif isNoun(concept):  ## prefix the :mod for nouns
         newNoun = N(nouns[concept].lemma)  # keep only noun from NP
         if ":A" in env:
             env.insertAfter(":A", ":A", newNoun)
         else:
             env.put(":A", newNoun)
         if neg: env.insertBefore(":A", ":A", Q("non"))
     elif isAdjective(concept):  ## postfix the :mod for adjectives
         newAdj = A(adjectives[concept].lemma)
         if ":A" in env:
             env.insertAfter(":A", ":A", newAdj)
         else:
             env.put(":A", newAdj)
         if neg: env.insertBefore(":A", ":A", Q("non"))
     elif isAdverb(concept):
         env.put(":D", Adv(concept))
     elif isVerb(concept):
         env.push(V(re.sub(r"-\d+$", '', concept)).t("pr"))
     elif semR.roles.areEmpty():  ## equivalent to processSimpleModOther
         env.push(Q(generateConceptWord(concept)))
     else:
         return False
     return True
Esempio n. 12
0
def getMorphVerb(s,myRole):
    vrb=morphVerbalizations[s]
    kind='actor' if myRole.startswith(":ARG0") and 'actor' in vrb else 'noun'
    return N(vrb[kind])
Esempio n. 13
0
determiners=set({"my","that","the","what","whatever","which","whichsoever","whose","a","this"})

### Conjunctions
def op16(conj):
    return LexSem(conj,"C",[":op1",":op2",":op3",":op4",":op5",":op6"],
                  lambda op1,op2,op3,op4,op5,op6:CP(C(conj),op1,op2,op3,op4,op5,op6))  
def op12(lemma,np,prep):
    return LexSem(lemma,"P",[":op1",":op2"],
                  lambda op1,op2:SP(np,op1,pp(prep,op2)))
conjunctions={}   
conjunctions["or"]=op16("or")
conjunctions["and"]=op16("and")
conjunctions["either"]=op16("either")
conjunctions["product-of"]=op16("times")
conjunctions["sum-of"]=op16("and")
conjunctions["ratio-of"]=op12("ratio-of",NP(N("ratio"),P("of")),"to")
conjunctions["difference-of"]=op16("minus")
conjunctions["quotient-of"]=op16("divided by")
conjunctions["power-of"]=op16("to the power of")
conjunctions["root-of"]= LexSem("root-of","P",[":op1",":op2"],
                                lambda op1,op2:NP(NO(op2[0].lemma).dOpt({"ord":True}),N("root"),PP(P("of"),op1)))
conjunctions["logarithm-of"]= LexSem("log-of","P",[":op1",":op2"],
                                     lambda op1,op2:NP(N("logarithm"),PP(P("of"),op1,N("base").a(":"),op2)))

def isConjunction(lemma):return lemma in conjunctions
def makeCP(lemma):
    return  conjunctions[lemma]

### Adverbs
adverbs["et-cetera"]=AdvP(Adv("etc"))
adverbs["at-least"]=AdvP(P("at"),Adv("least"))
Esempio n. 14
0
def wind(wInfo, period, lang):
    wind_terms = wInfo.get_wind(period)
    if wind_terms == None: return None
    lastSpeed = None
    lastDir = None
    jsrExprs = []
    for wind_term in wind_terms:
        wSpeed = wind_term.infos[2]
        wDir = wind_term.infos[0]
        jsrExpr = S()  # current expression
        if wSpeed >= 15 and wDir in jsrWindDirection:
            if lastSpeed != None and abs(
                    wSpeed - lastSpeed) >= 20:  # significant speed change
                lastSpeed = wSpeed
                if lang == "en":
                    jsrExpr.add(
                        VP(V("increase").t("pr"), PP(P("to"), NO(wSpeed))))
                else:
                    jsrExpr.add(
                        VP(V("augmenter").t("pr"), PP(P("à"), NO(wSpeed))))
            elif lastDir != None and dir_diff(
                    wDir, lastDir):  # significant direction change
                if lang == "en":
                    jsrExpr.add(
                        VP(V("become").t("pr"), jsrWindDirection[wDir][lang]))
                else:
                    jsrExpr.add(
                        VP(
                            V("devenir").t("pr"),
                            PP(P("de"), jsrWindDirection[wDir][lang])))
                lastDir = wDir
            else:  # realize wind and direction
                lastSpeed = wSpeed
                lastDir = wDir
                if lang == "en":
                    jsrExpr.add(
                        NP(N("wind"), jsrWindDirection[wDir][lang], NO(wSpeed),
                           Q("km/h")))
                else:
                    jsrExpr.add(
                        NP(
                            N("vent").n("p"),
                            PP(P("de"), jsrWindDirection[wDir][lang]),
                            PP(P("de"), NO(wSpeed), Q("km/h"))))
            if len(wind_term.infos) > 3:  # add gusting information
                gust = wind_term.infos[3]
                if gust.infos[0] == 'gust':
                    if lang == "en":
                        jsrExpr.add(
                            VP(
                                V("gust").t("pr"),
                                PP(P("to"), NO(gust.infos[1]))))
                    else:
                        jsrExpr.add(
                            PP(
                                P("avec"),
                                NP(
                                    N("rafale").n("p"), P("à"),
                                    NO(gust.infos[1]))))
            else:  # add time information
                jsrExpr.add(jsrHour(wind_term.start, lang))
            jsrExprs.append(jsrExpr)  # add current expression to the list
    return " ".join(realize(jsrExpr, lang, False) for jsrExpr in jsrExprs)
Esempio n. 15
0
from jsRealBclass import jsRealB, N, A, Adv, V, D, P, C, DT, NO, Q, NP, AP, AdvP, VP, S, PP, CP
from Realization.common import realize, jsrDayPeriod, jsrHour, get_max_term, get_min_term, get_term_at

### Pubpro sec 2.3.4
## vents : start end direction modif? speed value exception?
# e | nil | n | ne | nw | w | ely | nly | nely | nwly | wly | sly| sely | swly | sly | sely | sw | vrbl
jsrWindDirection = {
    "e": {
        "en": Adv("east"),
        "fr": NP(D("le"), N("est")),
        "deg": 90
    },
    "n": {
        "en": Adv("north"),
        "fr": NP(D("le"), N("nord")),
        "deg": 0
    },
    "ne": {
        "en": Adv("northeast"),
        "fr": NP(D("le"), N("nord-est")),
        "deg": 45
    },
    "nw": {
        "en": Adv("northwest"),
        "fr": NP(D("le"), N("nord-ouest")),
        "deg": 315
    },
    "w": {
        "en": Adv("west"),
        "fr": NP(D("le"), N("ouest")),
        "deg": 290
Esempio n. 16
0
        if len(env) > 0:
            ## add unprocessed args
            syntR.add(env.get(":start"), 0)
            syntR.add(env.get(".*"))
        return opts.apply(syntR)


pp = lambda prep, arg: PP(P(prep), arg) if arg != None else None
optD = lambda det: det if det != None else D("the")

verbs['give-01'] = LexSem(
    "V", "give", [":ARG0", ":ARG1", ":ARG2"],
    lambda arg0, arg1, arg2: S(arg0, VP(V("give"), arg1, pp("to", arg2))))

nouns['envelope'] = LexSem("envelope", "N", [":D", ":A"],
                           lambda d, a: NP(optD(d), a, N("envelope")))
nouns['boy'] = LexSem("boy", "N", [":D", ":A"],
                      lambda d, a: NP(optD(d), a, N("boy")))
nouns['girl'] = LexSem("girl", "N", [":D", ":A"],
                       lambda d, a: NP(optD(d), a, N("girl")))

adjectives["little"] = LexSem("little", "A", [], lambda: A("little"))
adjectives["nice"] = LexSem("nice", "A", [], lambda: A("nice"))

nounInfo = lambda lemma: LexSem(lemma, "N", [":D", ":A"], lambda d, a: NP(
    optD(d), a, N(lemma)))
adjInfo = lambda lemma: LexSem(lemma, "A", [], lambda: A(lemma))


def showSyntR(syntR):
    print(syntR)
Esempio n. 17
0
 def pcpn(type,action,tense,moment,quantity=None,unit=None):
 	return S(type,
 	         VP(V(action).t(tense),
 			    CP(PP(P("in"),NP(D("the"),N(moment))),
 				   None if quantity==None else NP(N("amount"),NP(NO(quantity),unit)))))
Esempio n. 18
0
def exampleRole(semR, env, opts):
    traceSyntR("exampleRole", semR)
    env.push(PP(P("for"), N("example").a(','), makeSyntR(semR)))
Esempio n. 19
0
def clearSavedJsrIO():
    savedJsrIO=[]

def getSavedJsrIO():
    return savedJsrIO

def realize(jsrExpr,lang,addS=True):
    if addS and not isinstance(jsrExpr,S):
        jsrExpr=S(jsrExpr)
    realization=jsRealB(jsrExpr.set_lang(lang).pp())
    if savedJsrIO!=None:
        savedJsrIO.append((jsrExpr.show(),realization))
    return realization

dayPeriods=[(0,5,{"en":lambda:NP(N("night")),"fr":lambda:NP(N("nuit"))}),
            (5,9,{"en":lambda:NP(Adv("early"),N("morning")),"fr":lambda:NP(N("début"),PP(P("de"),N("matinée")))}),
            (9,12,{"en":lambda:NP(N("morning")),"fr":lambda:NP(N("matin"))}),
            (12,18,{"en":lambda:NP(N("afternoon")),"fr":lambda:NP(N("après-midi"))}),
            (18,24,{"en":lambda:NP(N("tonight")),"fr":lambda:NP(N("soir"))}),
            ]

def jsrDayPeriod(hour,lang):
    isTomorrow=hour>23
    hour=hour%24
    for (s,e,jsrExp) in dayPeriods:
        if hour in range(s,e):
            exp=jsrExp[lang]()
            if isTomorrow:
                return exp.add(N("tomorrow" if lang=="en" else "demain"),0)
            elif s!=18:
Esempio n. 20
0
from jsRealBclass import jsRealB, N,A,Adv,V,D,P,C,DT,NO,Q, NP,AP,AdvP,VP,S,SP,PP,CP
from Realization.common import realize, jsrDayPeriod, jsrHour, get_max_term, get_min_term, get_term_at

precipitationTypes = {
    "showers":{"en":N("shower").n("p"), 
               "fr":N("averse").n("p")},
    "flurries":{"en":N("flurry").n("p"), 
                     "fr":NP(N("averse").n("p"),PP(P("de"),N("neige")))},
    "wet-flurries":{"en":NP(A("wet"),N("flurry").n("p")), 
                              "fr":NP(N("averse").n("p"),PP(P("de"),N("neige"),A("fondant")))},
    "blizzard":{"en":N("blizzard"), 
                "fr":N("blizzard")},
    "snow-squalls":{"en":NP(N("snow"),N("squall").n("p")), 
                         "fr":NP(N("bourrasque").n("p"),PP(P("de"),N("neige")))},
    "drizzle":{"en":N("drizzle"), 
              "fr":N("bruine")},
    "freezing-drizzle" :{"en":NP(V("freeze").t("pr"),N("drizzle")), 
                           "fr":NP(N("bruine"),A("verglaçant"))},
    "ice-crystals" :{"en":NP(N("ice"),N("crystal").n("p")), 
                       "fr":NP(N("cristal").n("p"),PP(P("de"),N("glace")))},
    "hail":{"en":N("hail"), 
             "fr":N("grêle")},
    "ice-pellets":{"en":NP(N("ice"),N("pellet").n("p")), 
              "fr":N("grésil")},
    "snow":{"en":N("snow"), 
             "fr":N("neige")},
    "wet-snow" :{"en":NP(A("wet"),N("snow")), 
                       "fr":NP(N("neige"),N("fondant"))},
    "thunderstorm":{"en":N("thunderstorm"), 
              "fr":N("orage").n("p")},
    "rain":{"en":N("rain"), 
Esempio n. 21
0
        syntR = self.lambda_(*argV)
        return opts.apply(syntR)
   
##   for unit testing
if __name__ == '__main__':
    def showSyntR(syntR):
        print(syntR.show())  # show the indented structure
        print(jsRealB(syntR.show(-1))) # get realized string

    ## a few lexicon entries
    verbs={}
    nouns={}

    verbs['give-01']=LexSem("V","give",[":ARG0",":ARG1",":ARG2"],
                            lambda arg0,arg1,arg2:S(arg0,VP(V("give"),arg1,pp("to",arg2))))    
    nouns['envelope'] = LexSem("envelope","N",[":D",":A"],lambda d,a:NP(optD(d),a,N("envelope")))
    nouns['boy']      = LexSem("boy","N",[":D",":A"],lambda d,a:NP(optD(d),a,N("boy")))
    nouns['girl']     = LexSem("girl","N",[":D",":A"],lambda d,a:NP(optD(d),a,N("girl")))

    boyEnv=Env([(':D',D("a"))])
    boyEnv.put(":A",A("nice")).put(":A",A("little"))
    boySyntR=nouns["boy"].apply(boyEnv,Options([("n","p")]))
    showSyntR(boySyntR) 
# NP(D("a"),
#    A("nice"),
#    A("little"),
#    N("boy")).n("p")
# nice little boys
    
    envelope=nouns["envelope"]
    envelopeSyntR=envelope.apply()
Esempio n. 22
0
            (5,   {"en":A("moderate"),                "fr":A("modéré")}), 
            (7,   {"en":A("high"),                    "fr":A("élevé")}), 
            (10,  {"en":AP(Adv("very"), A("high")),   "fr":AP(Adv("très"),A("élevé"))}), 
            (1000,{"en":A("extreme"),                 "fr":A("extrême")})]

def uv_index(wInfo,period,lang):
    if period in ["tonight","tomorrow_night"]:      # no UV index during the night
        return None
    uvi_terms=wInfo.get_uv_index(period)
    if uvi_terms==None:return None 
    uvVal=uvi_terms[0].infos[0]                     # consider only the first uvi_term
    if uvVal<1: return None                         # too low
    uvVal=round(uvVal)
    if uvVal==0:return None
    for high,expr in uv_ranges:
        if uvVal<=high:
            return realize(NP(Q("UV index" if lang=="en" else "indice UV"),
                              NO(uvVal),C("or" if lang=="en" else "ou"),expr[lang]),
                           lang)
    return None


if __name__ == '__main__':
    def showEnFr(jsrExprEN,jsrExprFR):
        print(f" %s\n %s\n"%(realize(jsrExprEN,"en",False),realize(jsrExprFR,"fr",False)))
## exercise all kinds of uv_ranges
    for i in range(0,len(uv_ranges)):
        (val,jsrEnFr)=uv_ranges[i]
        showEnFr(NP(Q("UV"),N("index"),NO(val),C("or"),jsrEnFr["en"]),
                 NP(N("indice"),Q("UV"),NO(val),C("ou"),jsrEnFr["fr"]))
        
Esempio n. 23
0
    if lang == "en":
        return S(
            N("temperature"),
            VP(V(trend).t("pr"), PP(P("to"), jsrTemp(goalTemp, lang)), when))
    else:
        return S(
            NP(N("température").n("p"), PP(P("à"), NP(D("le"), N(trend)))),
            PP(P("pour"),
               V("atteindre").t("b"), jsrTemp(goalTemp, lang), when))


jsrAbnormal = {
    "night": {
        "a": {
            "en":
            lambda t, _: temp_trend("en", "rise", t, PP(P("by"), N("morning"))
                                    ),
            "fr":
            lambda t, _: temp_trend("fr", "hausse", t, PP(
                P("en"), N("matinée")))
        },
        "b": {
            "en":
            lambda t, u: S(
                Adv("low"), u.a(","), P("with"),
                temp_trend("en", "rise", t, PP(P("by"), N("morning")))),
            "fr":
            lambda t, u: S(
                N("minimum"), u.a(","),
                temp_trend("fr", "hausse", t, PP(P("en"), N("matinée"))))
        },
Esempio n. 24
0
def haveDegree91(concept,roles,env,opts):
    traceSyntR("haveDegree91",concept)
    subject=None
    attribute=None
    comp=""
    quant=None
    if ":ARG1" in roles:
        arg1=roles[":ARG1"]
#         print("haveDegree1:",arg1.instanceIsRef())
        if not arg1.instanceIsRef(): # do not follow link for subject
            subject=makeSyntR(arg1)
    if ":ARG2" in roles:
        concept=roles[":ARG2"].concept
        attribute=makeSyntR(roles[":ARG2"])
        # HACK: remove spurious pronouns created by starrole
        if isinstance(attribute, AP) and len(attribute.elements)>1 and isinstance(attribute.elements[1],Pro):
            del attribute.elements[1]
            if len(attribute.elements)==1:
                attribute=attribute.elements[0]
    else:
        errorSyntR("have-degree-91 without :ARG2:%s"%concept)
        return Q("degree-91")
    if ":mod" in roles:
        if isinstance(attribute,Terminal):
            attribute=AP(attribute)
        attribute.add(makeSyntR(roles[":mod"]))        
    if ":ARG3" in roles:
        rolesARG3=roles[":ARG3"]
        deg=rolesARG3.get_concept()
        moreRoles=rolesARG3.get_roles()
        if moreRoles!=None and len(moreRoles)>0:
            if ":quant" in moreRoles:
                quant=makeSyntR(moreRoles[":quant"])
            else:
                attribute.add(makeSyntR(moreRoles[0][1]))
        if deg=="more":
            attribute=attribute.f("co")
            if quant!=None:
                attribute=NP(quant,attribute)
                quant=None
            comp="co"
        elif deg=="most":
            if isinstance(attribute,A):
                attribute=AP(D("the"),attribute.f("su"))
            else:
                attribute=AP(attribute,D("the"),Adv("most"))
            comp="su"
        elif deg in ["too","so","less"]:
            attribute=AdvP(Adv(deg),attribute)
            if deg=="less":
                comp="co"
            elif quant!=None:
                attribute=AP(attribute,quant)
                quant=None
        elif deg=="equal":
            attribute=AdvP(Adv("as"),attribute,Adv("as"))
        elif deg=="times":
            if quant!=None:
                quant=NP(quant,N("time"))
                attribute=attribute.f("co")
            comp="co"
        else:
            attribute=AdvP(attribute,Adv(deg))
    if ":ARG4" in roles:
        syntR4=makeSyntR(roles[":ARG4"])
        if comp=="co":
            attribute=PP(attribute,P("than"),syntR4)
            if quant!=None:
                attribute.add(quant,0)
        elif comp=="su":
            attribute=AP(attribute,Adv("in"),syntR4)
        else:
            attribute.add(syntR4)
    if ":ARG5" in roles:
        attribute.add(makeSyntR(roles[":ARG5"]))
    if ":ARG6" in roles:
        attribute=NP(attribute,makeSyntR(roles[":ARG6"]))
#     print("have-degree-91:subject:",subject)
    while ":li" in roles:
        semR=roles[":li"]
        del roles[":li"]
        ## analogous to roleProcessing.lirole
        semR_i=unquote(semR.get_instance())
        if semR_i=="-1":
            attribute.add(Adv("lastly"),0)
        elif semR_i=="1":
            attribute.add(Adv("first"),0)
        elif is_number(semR_i):
            attribute.add(Q("("+str(semR_i)+")"),0)
        elif semR_i[0]=='"':
            attribute.add(Q("("+semR_i+")"),0)
    restRoles=addRoles(concept, roles, [":ARG1",":ARG2",":ARG3",":ARG4",":ARG5",":ARG6",":li",":mod",":polarity"], 
                       LexSem("degree","SP",[],lambda:SP()),env, opts)        
    if len(restRoles.elements)>0:
        attribute=ensurePhrase(attribute).add(restRoles)
    if subject!=None:
        attribute=predicate(subject,attribute)
        if hasNegPolarity(roles):
            return attribute.typ({"neg":True})
    else:
        if hasNegPolarity(roles):
            return AdvP(Adv("not"),attribute)
    return attribute
Esempio n. 25
0
def exemplifyEntity(concept,roles,env,opts):
    traceSyntR("exemplifyEntity",concept)
    if roles.areEmpty():
        return PP(P("for"),N("example"))
    return None
Esempio n. 26
0
def dateEntity(concept,roles,env,opts):
    def zPad(s): #ensure a string of length 2 padded with a 0 
        if len(s)==2: return s
        if len(s)==1: return "0"+s
        if len(s)>2 : return s[0:2]
        return s
    
    def checkDateComp(date,rName,dOptField,length,default):
        if rName in roles:
            val=roles[rName].instance
            if is_number(val) and len(val)<=length:
                date+=val.rjust(length,"0")
                dOpt[dOptField]=True
            else:
                print("dateEntity: strange %s:%s"%(rName,val))
                date+=default
        else:
            date+=default
        return date
    
    traceSyntR("dateEntity",concept)
    if ":time" in roles and roles[":time"].get_concept()=="amr-unknown":
        return Q("what time is it ?")
    date="" # ISO format "YYYY-MM-DDTHH:mm:ss"
    dOpt={"year":False , "month":False , "date":False , "day":False , "hour":False , 
          "minute":False , "second":False , "nat":True, "det":False, "rtime":False}
    date=checkDateComp(date,":year","year",4,"2021")+"-"
    date=checkDateComp(date,":month", "month", 2, "01")+"-"
    date=checkDateComp(date,":day", "date", 2, "01")+"T"
    if ":time" in roles:
        timeS=roles[":time"].instance
        if isinstance(timeS,str) and ":" in timeS:
            time=unquote(timeS)
            tParts=time.split(":")
            if len(tParts)==2:
                tParts.append("00")
            if len(tParts)==3:
                date+=zPad(tParts[0])+":"+zPad(tParts[1])+":"+zPad(tParts[2])
                dOpt["hour"]=True
                dOpt["minute"]=True
                dOpt["second"]=True
    if not dOpt["hour"]:
        date+="00:00:00"
        dOpt["hour"]=False
        dOpt["minute"]=False
        dOpt["second"]=False
    sp=SP(DT(date+"-05:00").dOpt(dOpt))## HACK: force Montreal time zone  
    if ":timezone" in roles:
        sp.add(makeSyntR(roles[":timezone"]))
    if ":weekday" in roles:
        sp.add(Q(unquote(roles[":weekday"].get_concept()).capitalize()),0)
    if ":season" in roles:
        sp.add(Q(unquote(roles[":season"].get_concept())),0)
    if ":mod" in roles:
        sp.add(Q(unquote(roles[":mod"].get_concept())),0)
    if ":dayperiod" in roles:
        sp.add(Q(unquote(roles[":dayperiod"].get_concept())))
    if ":quarter" in roles:
        sp.add(NP(makeSyntR(roles[":quarter"]).dOpt({"ord":True}),N("quarter")))
    if ":year2" in roles:
        sp.add(makeSyntR(roles[":year2"]).dOpt({"raw":True}).b("-"))
    if ":era" in roles:
        sp.add(Q(unquote(roles[":era"].get_instance())))
    if ":calendar" in roles:
        sp.add(N("calendar").a(":"))
        sp.add(makeSyntR(roles[":calendar"]))
    if ":decade" in roles:
        sp.add(makeSyntR(roles[":decade"]))
        sp.add(Q("s"))
    return sp
Esempio n. 27
0
from jsRealBclass import N,A,Adv,V,D,P,C,DT,NO,Q, NP,AP,AdvP,VP,S,PP,CP
from Realization.common import realize, jsrDayPeriod

sky_condition_terminology = { ## types of sky conditions
    "c1":{"en":(AP(A("sunny")),AP(A("clear"))),
          "fr":(AP(A("ensoleillé")),AP(A("dégagé")))},
    "c2":{"en":(AP(Adv("mainly"),A("sunny")),NP(Q("a"),D("few"),N("cloud").n("p"))),
          "fr":(AP(Adv("généralement"),A("ensoleillé")),NP(D("quelque"),N("nuage").n("p")))},
    "c3":{"en":(NP(D("a"),N("mix"),PP(P("of"),CP(C("and"),N("sun"),N("cloud").n("p")))),
                AP(Adv("partly"),A("cloudy"))),
          "fr":(NP(N("alternance"),CP(C("et"),PP(P("de"),N("soleil")),PP(P("de"),N("nuage").n("p")))),
                AP(Adv("partiellement"),A("couvert")))},
    "c4":{"en":(AP(Adv("mainly"),A("cloudy")),),
          "fr":(AP(Adv("généralement"),A("nuageux")),)},
    "c5":{"en":(AP(A("cloudy")),),
          "fr":(AP(A("nuageux")),)},
    "c6":{"en":(AP(A("overcast")),),
          "fr":(AP(A("couvert")),)},
    "c7":{"en":(NP(V("increase").t("pr"),N("cloudiness")),),
          "fr":(NP(N("ennuagement")),)},
    "c8":{"en":(NP(N("clearing")),),
          "fr":(NP(N("dégagement")),)},
}

def sky_condition(mc,period,lang):
    previous_conditions=[]
    jsrExprs=[]

    def addNoRepeat(c,dn,period=None): # avoid generating same sentence twice
        if c not in previous_conditions:
            if len(sky_condition_terminology[c][lang])==1:dn=0