How to use prolog method in autotest

Best Python code snippet using autotest_python

qpro.py

Source:qpro.py Github

copy

Full Screen

...51 prof=fd+"pro/"+fn52 txtf=dr.trimSuf(path)53 #print(txtf,'->',prof)54 print('GENERATING:',prof+".pro")55 export_to_prolog(txtf,prof)56# interactive dialog57def talk_about(fNameNoSuf,params=params):58 return dialog_about(fNameNoSuf,None,params=params)59def dialog_about(fNameNoSuf,question,params=params) :60 gm=export_to_prolog(fNameNoSuf,params=params)61 if params.show: gm.kshow(params.cloud,file_name="cloud.pdf",show=True)62 if params.summarize :63 print(gm)64 #for x in dr.best_edges(100,gm) : print('BEST EDGE',x)65 B=dr.best_line_graph(32,gm)66 gshow(B,attr="rel")67 prolog = Prolog()68 sink(prolog.query("consult('" + pro() + "')"))69 sink(prolog.query("load('"+fNameNoSuf+"')"))70 qgm=dr.GraphMaker(params=params)71 M = []72 log=[]73 if isinstance(question,list):74 for q in question :75 say(q)76 process_quest(prolog,q, M, gm, qgm, fNameNoSuf,log,params=params)77 elif question :78 say(question)79 print('')80 dialog_step(prolog,question,gm,qgm,fNameNoSuf,log,params=params)81 else :82 while(True) :83 question=input('?-- ')84 if not question : break85 process_quest(prolog,question, M, gm, qgm, fNameNoSuf,log,params=params)86 return process_log(log)87def process_log(log) :88 l=len(log)89 qa_log=dict()90 for i in range(l) :91 ls=[]92 for a in log[i][1] :93 snum=a.split(':')[0]94 ls.append(int(snum))95 qa_log[i]=ls96 return qa_log97def process_quest(prolog,question,M,gm,qgm,fNameNoSuf,log,params=params) :98 question = question + ' '99 if question in M:100 i = M.index(question)101 M.pop(i)102 M.append(question)103 if params.quest_memory>0 : M=M[-params.quest_memory:]104 Q=reversed(M)105 question = ''.join(Q)106 dialog_step(prolog, question, gm, qgm, fNameNoSuf,log,params=params)107# step in a dialog agent based given file and question108def dialog_step(prolog,question,gm,qgm,fNameNoSuf,log,params=params) :109 query_to_prolog(question,gm,qgm,fNameNoSuf,params=params)110 rs=prolog.query("ask('" + fNameNoSuf + "'" + ",Key)")111 answers=[pair['Key'] for pair in rs]112 log.append((question,answers))113 if not answers: say("Sorry, I have no good answer to that.")114 else :115 for answer in answers :116 say(answer)117 print('')118def sink(generator) :119 for _ in generator : pass120def getNERs(ws):121 from nltk.parse.corenlp import CoreNLPParser122 from textcrafts.corenlp_api import parserURL123 parser = CoreNLPParser(url=parserURL, tagtype='ner')124 ts = parser.tag(ws)125 for t in ts :126 if t[1] !='O' :127 yield t128# sends dependency triples to Prolog, as rececived from Parser129def triples_to_prolog(pref,qgm,f) :130 ctr=0131 for ts in qgm.triples() :132 for x in ts:133 (fr,ft),r,(to,tt)=x134 print(pref+'dep',end='',file=f)135 print((ctr,fr,ft,r,to,tt),end='',file=f)136 print('.',file=f)137 ctr+=1138def sents_to_prolog(pref, qgm, f):139 #s_ws_gen=dr.sent_words(qgm)140 s_ws_gen=enumerate(qgm.words())141 for s_ws in s_ws_gen:142 print(pref + 'sent', end='', file=f)143 print(s_ws, end='', file=f)144 print('.', file=f)145def ners_to_prolog(pref, qgm, f):146 if not params.corenlp :147 return148 #print("GENERATING NERS")149 s_ws_gen=enumerate(qgm.words())150 for s_ws in s_ws_gen:151 s,ws=s_ws152 ners=list(enumerate(getNERs(ws)))153 if ners:154 print(pref + 'ner', end='', file=f)155 print((s,ners), end='', file=f)156 print('.', file=f)157# sends summaries to Prolog158def sums_to_prolog(pref,k,qgm,f) :159 if pref : return160 for sent in qgm.bestSentences(k) :161 print('summary',end='',file=f)162 print(sent,end='',file=f)163 print('.',file=f)164# sends keyphrases to Prolog165def keys_to_prolog(pref,k,qgm,f) :166 if pref : return167 for kw in qgm.bestWords(k) :168 print(pref+"keyword('",end='',file=f)169 print(kw,end="')",file=f)170 print('.',file=f)171# sends edges of the graph to Prolog172def edges_to_prolog(pref,qgm,f) :173 for ek in qgm.edgesInSent() :174 e,k=ek175 a,aa,r,b,bb=e176 e = (k,a,aa,r,b,bb)177 print(pref+'edge',end='',file=f)178 print(e,end='',file=f)179 print('.',file=f)180 if params.show and pref :181 dr.query_edges_to_dot(qgm)182# generic Prolog predicate maker183def facts_to_prolog(pref,name,facts,f) :184 if isinstance(facts,dict) :185 facts=facts.items()186 for fact in facts :187 print(pref+name,end='',file=f)188 print(fact,end='',file=f)189 print('.',file=f)190 print('',file=f)191# sends the computed ranks to Prolog192def ranks_to_prolog(pref,qgm,f) :193 ranks=qgm.pagerank()194 facts_to_prolog(pref, 'rank', ranks, f)195# sends the words to lemmas table to Prolog196def w2l_to_prolog(pref,qgm,f) :197 tuples=qgm.words2lemmas198 for r in tuples :199 print(pref+'w2l',end='',file=f)200 print(r,end='',file=f)201 print('.',file=f)202# sends svo realtions to Prolog203def svo_to_prolog(pref,qgm,f) :204 rs=qgm.bestSVOs(100)205 facts_to_prolog(pref, 'svo', rs, f)206# sends a similarity relation map to Prolog207def sims_to_prolog(pref,gm,qgm,f) :208 #print(qgm.words)209 for qs in qgm.words2lemmas :210 qw,ql,qt=qs211 for cs in gm.words2lemmas :212 cw,cl,ct=cs213 if ql!=cl : # and qt==ct:214 if is_similar(ql,qt,cl,ct):215 print('query_sim',end='',file=f)216 print((ql,qt,cl,ct),end='',file=f)217 print('.',file=f)218# sends a similarity relation map to Prolog219def rels_to_prolog(pref,gm,qgm,f) :220 def sentId(touple) :221 return touple[3]222 pr=gm.pagerank()223 ws=dict()224 rels=set()225 i=0226 for w in pr :227 if dr.isWord(w) :228 ws[w]=i229 i+=1230 for qs in qgm.words2lemmas :231 _,ql,qt=qs232 wn_tag=pos2tag(qt)233 if wn_tag!='n' : continue234 hypers=wn_hyper(3,ql,wn_tag)235 hypos=wn_hypo(3,ql,wn_tag)236 meros=wn_mero(3,ql,wn_tag)237 holos=wn_holo(3,ql,wn_tag)238 for h in hypers :239 if h in ws :240 rels.add((ql,'is_a',h,-ws[h])) # order in ranks = -ws[h]241 for h in hypos :242 if h in ws :243 rels.add((h,'is_a',ql,-ws[h]))244 for h in meros :245 if h in ws :246 rels.add((h,'part_of',ql,-ws[h]))247 for h in holos :248 if h in ws :249 rels.add((ql,'part_of',h,-ws[h]))250 rels=sorted(rels,key=sentId,reverse=True)251 facts_to_prolog(pref,'rel',rels,f)252# exporting to Prolog files needed to answer query253def export_to_prolog(fNameNoSuf,OutF=None,params=params) :254 gm=dr.GraphMaker(params=params)255 gm.load(fNameNoSuf+'.txt')256 if not OutF :257 OutF = fNameNoSuf258 to_prolog('',gm,gm,OutF,params=params)259 return gm260def params_to_prolog(pref,f,params=params) :261 rels=[('quest_memory',params.quest_memory),262 ('max_answers', params.max_answers),263 ('repeat_answers',params.repeat_answers),264 ('personalize',params.personalize),265 ('by_rank', params.by_rank)266 ]267 facts_to_prolog(pref, 'param', rels, f)268def personalize_for_query(gm, qgm, sk, wk):269 query_dict = dr.pers_dict(qgm)270 ranks = gm.rerank(query_dict)271 if params.show: gm.kshow(params.cloud, file_name="quest_cloud.pdf", show=True)272 def ranked(xs):273 # return xs274 for x in xs:275 yield x, ranks.get(x)276 # sents = [(w, r) for (w, r) in ranks if isinstance(w, int)]277 # words = [(w, r) for (w, r) in ranks if isinstance(w, str)]278 sents = ranked([x for (x, _) in gm.bestSentencesByRank(sk)])279 words = ranked(gm.bestWords(wk))280 # print('WORDS',words)281 return (sents, words)282# process a query and send it to Prolog283def query_to_prolog(text,gm,qgm,fNameNoSuf,params=params) :284 qgm.digest(text)285 qfName=fNameNoSuf+'_query'286 to_prolog('query_',gm,qgm,qfName,params=params)287def personalized_to_prolog(pref,gm,qgm,personalize,f) :288 count=personalize289 #print("COUNT",count)290 assert(isinstance(count,int))291 (sents,words) = personalize_for_query(gm,qgm,count,count)292 facts_to_prolog(pref, 'pers_sents', sents, f)293 facts_to_prolog(pref, 'pers_words', words, f)294# sends several fact predicates to Prolog295# small files are used that the pyswip activated Prolog will answer296# the pref='query_' marks file names with query_, while297# the empty prefix pref='' marks realtions describing a document298def to_prolog(pref,gm,qgm,fNameNoSuf,params=params) :299 with open(fNameNoSuf+'.pro','w') as f :300 triples_to_prolog(pref,qgm,f)301 #print(' ',file=f)302 edges_to_prolog(pref,qgm,f)303 print(' ',file=f)304 ranks_to_prolog(pref,qgm,f)305 print(' ',file=f)306 w2l_to_prolog(pref,qgm,f)307 print(' ',file=f)308 sents_to_prolog(pref,qgm,f)309 print(' ',file=f)310 ners_to_prolog(pref, qgm, f)311 print(' ', file=f)312 svo_to_prolog(pref,qgm,f)313 print(' ',file=f)314 if pref : # query only315 #sims_to_prolog(pref,gm,qgm,f)316 rels_to_prolog(pref,gm,qgm,f) # should be after svo!317 if params.personalize>0 :318 personalized_to_prolog(pref,gm,qgm,params.personalize,f)319 params_to_prolog(pref, f,params=params)320 else : # document only321 sums_to_prolog(pref,10,qgm,f)322 print(' ',file=f)323 keys_to_prolog(pref,10,qgm,f)324 print(' ',file=f)325# turns a sequence/generator into a file, one line per item yield326def seq2file(fname,seq) :327 xs=map(str,seq)328 ys=interleave_with('\n','\n',xs)329 text=''.join(ys)330 string2file(fname,text)331# turns a file into a (string) generator yielding each of its lines332def file2seq(fname) :333 with open(fname,'r') as f :334 for l in f : yield l.strip()335# turns a string into given file336def string2file(fname,text) :337 with open(fname,'w') as f :...

Full Screen

Full Screen

main.py

Source:main.py Github

copy

Full Screen

1import os2import random3import sys4import asyncio5import telepot6from telepot.aio.loop import MessageLoop7from telepot.aio.delegate import pave_event_space, per_chat_id, create_open8from pyswip import Prolog9from keyboard import generateKB, ReplyKeyboardRemove10import replies11from telegram_token import TOKEN12from prolog_convertor import PrologConvertor13class TelegramBot(telepot.aio.helper.ChatHandler):14 def __init__(self, *args, **kwargs):15 super(TelegramBot, self).__init__(*args, **kwargs)16 self.prolog = PrologConvertor()17 self.question_lists = ['meals', 'breads', 'mains', 'veggies', 'sauces', 'topups', 'sides', 'drinks']18 self.counter = 019 def __restart(self):20 self.prolog = PrologConvertor()21 self.counter = 022 async def __updateCounter(self):23 next_question = self.question_lists[self.counter + 1]24 if self.prolog.available_options(next_question):25 self.counter += 126 else:27 self.counter += 228 async def __ask(self, id, bot, question):29 if question == 'meals':30 meals = self.prolog.selectable_input_options(question)31 await bot.sendMessage(32 id, 33 replies.getWelcome(34 meal_options=meals, 35 restart=False36 ),37 reply_markup=generateKB(meals)38 )39 elif question == 'breads':40 breads = self.prolog.selectable_input_options(question)41 await bot.sendMessage(42 id, 43 replies.getAskBreads(bread_options=breads),44 reply_markup=generateKB(breads)45 )46 elif question == 'mains':47 mains = self.prolog.selectable_input_options(question)48 await bot.sendMessage(49 id, 50 replies.getAskMains(main_options=mains),51 reply_markup=generateKB(mains)52 )53 elif question == 'veggies':54 veggies = self.prolog.selectable_input_options(question)55 await bot.sendMessage(56 id, 57 replies.getAskVeggies(veggie_options=veggies),58 reply_markup=generateKB(veggies, add_skip=True)59 )60 elif question == 'sauces':61 sauces = self.prolog.selectable_input_options(question)62 63 await bot.sendMessage(64 id, 65 replies.getAskSauces(sauce_options=sauces),66 reply_markup=generateKB(sauces, add_skip=True)67 )68 elif question == 'topups':69 topups = self.prolog.selectable_input_options(question)70 await bot.sendMessage(71 id, 72 replies.getAskTopups(topup_options=topups),73 reply_markup=generateKB(topups, add_skip=True)74 )75 elif question == 'sides':76 sides = self.prolog.selectable_input_options(question)77 await bot.sendMessage(78 id, 79 replies.getAskSides(side_options=sides),80 reply_markup=generateKB(sides, add_skip=True)81 )82 elif question == 'drinks':83 drinks = self.prolog.selectable_input_options(question)84 await bot.sendMessage(85 id, 86 replies.getAskDrinks(drink_options=drinks),87 reply_markup=generateKB(drinks)88 )89 else:90 await bot.sendMessage(91 id, 92 replies.getOrderSummary(93 meals=self.prolog.selected_options("meals"),94 breads=self.prolog.selected_options("breads"), 95 mains=self.prolog.selected_options("mains"), 96 veggies=self.prolog.selected_options("veggies"), 97 sauces=self.prolog.selected_options("sauces"), 98 topups=self.prolog.selected_options("topups"), 99 sides=self.prolog.selected_options("sides"),100 drinks=self.prolog.selected_options("drinks")101 ),102 reply_markup=ReplyKeyboardRemove(),103 parse_mode='HTML'104 )105 await bot.sendMessage(106 id, "Preping for your meal... It will be ready soon..."107 )108 await bot.sendDocument(109 id, document=open('images/order_completed.gif', 'rb')110 )111 await bot.sendMessage(112 id, "Enjoy!"113 )114 await bot.sendMessage(115 id, "Want to start a new order? Click /restart"116 )117 async def on_chat_message(self, msg):118 _, _, id = telepot.glance(msg)119 if msg['text'] == '/start':120 self.__restart()121 await self.__ask(id, bot, self.question_lists[self.counter])122 elif msg['text'] == '/restart':123 self.__restart()124 meals = self.prolog.available_options("meals")125 126 await bot.sendMessage(127 id, 128 replies.getWelcome(129 meal_options=meals, 130 restart=True131 ),132 reply_markup=generateKB(meals)133 )134 else:135 user_input = msg['text'].lower().replace(" ", "_")136 if user_input not in self.prolog.all_options("drinks"):137 if "skip" in user_input:138 await self.__updateCounter()139 140 elif user_input in self.prolog.all_options("meals"):141 self.prolog.add_meal(user_input)142 await self.__updateCounter()143 elif user_input in self.prolog.all_options("breads"):144 self.prolog.add_bread(user_input)145 await self.__updateCounter()146 elif user_input in self.prolog.all_options("mains"):147 self.prolog.add_main(user_input)148 await self.__updateCounter()149 elif user_input in self.prolog.all_options("veggies"):150 self.prolog.add_veggie(user_input)151 152 if not self.prolog.selectable_input_options("veggies"):153 await self.__updateCounter()154 155 elif user_input in self.prolog.all_options("topups"):156 self.prolog.add_topup(user_input)157 if not self.prolog.selectable_input_options("topups"):158 await self.__updateCounter()159 160 elif user_input in self.prolog.all_options("sauces"):161 self.prolog.add_sauce(user_input)162 if not self.prolog.selectable_input_options("sauces"):163 await self.__updateCounter()164 165 elif user_input in self.prolog.all_options("sides"):166 self.prolog.add_side(user_input)167 if not self.prolog.selectable_input_options("sides"):168 await self.__updateCounter()169 170 await self.__ask(id, bot, self.question_lists[self.counter])171 else:172 self.prolog.add_drink(user_input)173 await self.__ask(id, bot, None)174bot = telepot.aio.DelegatorBot(TOKEN, [175 pave_event_space()(176 per_chat_id(), create_open, TelegramBot, timeout=500),177])178loop = asyncio.get_event_loop()179loop.create_task(MessageLoop(bot).run_forever())180print('Listening...')...

Full Screen

Full Screen

prolog_convert.py

Source:prolog_convert.py Github

copy

Full Screen

1from pyswip import Prolog, prolog2PROLOG_FILENAME = "prolog_code.pl"3class PrologConvertor():4 def __init__(self):5 self.prolog = Prolog()6 self.prolog.consult(PROLOG_FILENAME)7 self.__retractall()8 def __retractall(self):9 self.prolog.retractall("selected_meals(X)")10 self.prolog.retractall("selected_breads(X)")11 self.prolog.retractall("selected_mains(X)")12 self.prolog.retractall("selected_veggies(X)")13 self.prolog.retractall("selected_sauces(X)")14 self.prolog.retractall("selected_topups(X)")15 self.prolog.retractall("selected_sides(X)")16 self.prolog.retractall("selected_drinks(X)")17 def all_options(self, category):18 res = list(self.prolog.query("all_options({}, X)".format(category)))[0]["X"]19 return self.convert_res_to_list(res)20 def available_options(self, category):21 res = list(self.prolog.query("available_options({}, X)".format(category)))22 return res if res == [] else self.convert_res_to_list(res[0]["X"])23 def selected_options(self, category):24 res = list(self.prolog.query("selected_options({}, X)".format(category)))25 return res if res == [] else self.convert_res_to_list(res[0]["X"])26 def selectable_input_options(self, category):27 return list(set(self.available_options(category)) - set(self.selected_options(category)))28 def add_meal(self, X):29 self.prolog.assertz("selected_meals({})".format(X))30 def add_bread(self, X):31 self.prolog.assertz("selected_breads({})".format(X))32 def add_main(self, X):33 self.prolog.assertz("selected_mains({})".format(X))34 def add_veggie(self, X):35 self.prolog.assertz("selected_veggies({})".format(X))36 37 def add_topup(self, X):38 self.prolog.assertz("selected_topups({})".format(X))39 def add_sauce(self, X):40 self.prolog.assertz("selected_sauces({})".format(X))41 def add_side(self, X):42 self.prolog.assertz("selected_sides({})".format(X))43 def add_drink(self, X):44 self.prolog.assertz("selected_drinks({})".format(X))45 def convert_res_to_list(self, res):46 counter = 047 result = []48 while (counter < len(res)):49 result.append(res[counter].value)50 counter += 1...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful