def loop(self): ui.draw_all() try: while True: if self.player.death: if self.wizard: if ui.prompt('Die? [yn]', 'yn') == 'n': ui.new_ui_turn() self.player.resurrect() ui.draw_all() continue ui.prompt( '[Game over: %s. Press ENTER]' % self.player.death, [T.KEY_ENTER, T.KEY_KPENTER]) self.save_character_dump() raise Quit() if self.player.won: ui.prompt( 'Congratulations! You have won. Press ENTER', [T.KEY_ENTER, T.KEY_KPENTER]) self.save_character_dump() raise Quit() while self.player.action_turns > 0: key = ui.readkey() self.do_command(key) self.map.do_turn(self.turns) self.turns += 1 ui.draw_all() except Quit: pass
def askForever(question): answer = "" time = 0 ui.tell(question) ui.prompt() while True: time = time + 1 answer = ui.listen() if answer == "" and time < 4: ui.tell("\n") ui.tell(phrasebase.getReply("waiting")) ui.prompt() if answer == "" and time >= 4 and time < 7: ui.tell("\n") ui.tell(phrasebase.getReply("worried_waiting")) ui.prompt() if time >= 7 and time < 10: continue if time >= 10: ui.tell("\n") ui.tell("It seems that you are a bit distracted right now. Or maybe dead. ... ...I hope you are not dead. But because it's been a while since your last answer...") ui.prompt() if askbreak(): time = 0 ui.tell("So my question was: " + question) ui.prompt() continue else: goodbye() break if answer != "": return answer
def processPDFs(dirname): images = [] targets = [] # Choose to load old images or create new ones options = ["Load", "Create"] res = ui.prompt("Load pre-processed images or create new ones?", options) filetype = ".bmp" if res == "0" else ".file" # Select a type message = None if options[int(res)] == "Create": message = "Select an visualization type:" else: message = "Which type of plot are these images?" options = ["Byte Map", "Markov Plot"] res = ui.prompt(message, options) type = options[int(res)] for file in pb.progressbar(os.listdir(dirname)): # Iterate through files if file.endswith(filetype): # Check if right file type filepath = os.path.join(dirname, file) if filetype == ".bmp": # We are just loading an image here images.append(cv2.imread(filepath)) targets.append(file[:5]) # Either "CLEAN" or "INFEC" elif filetype == ".file": # Creating new images here if type == "Byte Map": images.append(create_bmp(filepath)) elif type == "Markov Plot": images.append(create_markov(filepath)) cv2.imwrite("{}.bmp".format(filepath), images[-1]) targets.append(file[:5]) # Either "CLEAN" or "INFEC" return images, targets, type
def train(data, targets, filenames): targets = [val == "INFEC" for val in targets] # Set INFEC as positive val # Choose training mode options = ["Cross validation", "Build and test model"] res = ui.prompt(options=options) mode = options[int(res)] # Choose ML algorithm options = ["Support Vector Machine", "Random Forest", "Decision Tree Classifier", "KNN"] res = ui.prompt("Choose a ML algorithm:", options) switch = { 0: svm.SVC(C=100., random_state=0), 1: RandomForestClassifier(n_estimators=50, max_depth=None, random_state=0), 2: DecisionTreeClassifier(random_state=0), 3: KNeighborsClassifier() } clf = switch.get(int(res)) if mode == "Cross validation": model_evaluation(data, targets, clf) elif mode == "Build and test model": # Train model clf.fit(data, targets) # Get test dir while True: dirname = ui.prompt("Which directory are the test files in?") if os.path.isdir(dirname): break print("ERROR: Directory not found.") # Set up data/targets for test model print("\n************************************") print("* PREPARING MODEL FOR EVALUATION *") print("************************************") pageNames, y_true, filenames = pproc.process(dirname) y_true = [val == "INFEC" for val in y_true] # Set INFEC as positive val test_data = ft.features(pageNames) y_pred = clf.predict(test_data) save_filenames(y_true, y_pred, filenames) conf_matrix = skm.confusion_matrix(y_true, y_pred) accuracy = skm.accuracy_score(y_true, y_pred) precision = skm.precision_score(y_true, y_pred, average=None) recall = skm.recall_score(y_true, y_pred, average=None) f1 = skm.f1_score(y_true, y_pred, average=None) print("\n{}".format(conf_matrix)) print("Accuracy: {}".format(accuracy)) print("Precision: {}".format(precision[1])) print("Recall: {}".format(recall[1])) print("F1: {}".format(f1[1]))
def ainspect(): #function för att printa en del utav ui ui.clear() #Clear call ui.line(False) # printar en linje gjord utav * ui.header("ARTIST DATABASE") ui.line(True) # printar en linje gjord utav - web.inspectart() #kallar på funktionen som tar fram informationen på specifika artister. ui.line(False) # printar en linje gjord utav * ui.echo("| Press enter to return ") # Printar våra val ui.line(False) # printar en linje gjord utav * ui.prompt()
def alist(): #function för att printa en del utav ui ui.clear() #Clear call ui.line(False) # printar en linje gjord utav - ui.header("ARTIST DATABASE") ui.line(True) # printar en linje gjord utav * web.getart() #kallar på funktionen som tar fram listna av artister ui.line(False) # printar en linje gjord utav - ui.echo("| Press enter to return ") # Printar våra val ui.line(False) # printar en linje gjord utav - ui.prompt()
def train(data, targets, plotType, ftType): options = [ "Support Vector Machine", "Random Forest", "Decision Tree Classifier", "KNN" ] res = ui.prompt("Choose a ML algorithm:", options) clfType = options[int(res)] switch = { 0: svm.SVC(C=100.), 1: RandomForestClassifier(max_depth=2), 2: DecisionTreeClassifier(), 3: KNeighborsClassifier() } clf = switch.get(int(res)) # Split-out test dataset and randomize order seed = 42 # Seeded so as to create reproducible results validation_size = 0.20 x_train, x_test, y_train, y_test = model_selection.train_test_split( data, targets, test_size=validation_size, random_state=seed) # Fit model clf.fit(x_train, y_train) y_pred = clf.predict(x_test) # Show confusion matrix for this fit unique, counts = np.unique(y_pred, return_counts=True) counts = dict(zip(unique, counts)) print("\nPredictions: {}".format(counts)) print("Confusion Matrix:\n{}".format(confusion_matrix(y_test, y_pred))) # Cross validate and calculate scores scoring = ["accuracy", "precision", "recall", "f1"] # Choose scoring methods targets = [val == "INFEC" for val in targets] # Set INFEC as positive val scores = cross_validate(clf, data, targets, scoring=scoring, cv=5) print("Scores calculated from 5-fold cross validation:") print("Accuracy: {},\t{}".format( round(np.mean(scores["test_accuracy"]), 4), scores["test_accuracy"])) print("Precision: {},\t{}".format( round(np.mean(scores["test_precision"]), 4), scores["test_precision"])) print("Recall: {},\t{}".format(round(np.mean(scores["test_recall"]), 4), scores["test_recall"])) print("F1: {},\t{}".format(round(np.mean(scores["test_f1"]), 4), scores["test_f1"])) # Plot Learning Curve options = ["Yes", "No"] res = ui.prompt("Plot learning curve?", options) if options[int(res)] == "Yes": title = "Learning Curve ({}, {}, {})".format(clfType, ftType, plotType) # plot_learning_curve(clf, title, data, targets, ylim=(0.7, 1.01), cv=5, n_jobs=4) plot_learning_curve(clf, title, data, targets, cv=5, n_jobs=4) plt.show()
def inspectart(): #funktionen som kombinerar urlen med artist Id så att vi kan komma åt djupare element i api'n. url = 'https://5hyqtreww2.execute-api.eu-north-1.amazonaws.com/artists/'#tar samma url som innan. r = requests.get(url) #sparar ned urlen i variabeln R svar = r.json() #gör om json listan så att vi kan använda den. artists = svar["artists"] #gör så att vi kan ta ut informationen med nyckel ordet Artists val = ui.prompt() #kallar på promt funktionen så att vi kan göra ett val utav vilken artist vi vill åt. for artist in artists: #itererar igenom våra artister så att vi kan komma längre in i dictionariet. if val.title() == artist["name"]: #kollar så att artisten i loopen nu stämmer med vårat val. ui.line(True) # printar en linje gjord utav - Aid = artist["id"] #sparar ned Id's på våran matchande artist. newurl= str(url + Aid) #tar Id's och kombinerar det med våran url z = requests.get(newurl) #gör en request emot den nya urlen inspection = z.json()#sparar ned json objektet så att programmet kan agera med det. ui.echo("Name: " + inspection["artist"]["name"]) ui.echo(" ") ui.echo("Genres") for genre in inspection["artist"]["genres"]:#loopar och printar ut genres på våra artister ui.echo(genre) ui.echo(" ") for years in inspection["artist"]["years_active"]:#loopar igenom och printar ut de åren som gruppen var aktiv ui.echo("Years active: " + years) print(" ") ui.echo("Members") for member in inspection["artist"]["members"]:#loopar igenom och printar ut de medlemar i bandet och deras stagenames, har de inte det så printar det bandnamnet. ui.echo(member)
def features(pageNames): """Loop through images, extracting desired features""" options = ["ORB", "SIFT", "LBP", "Gabor", "Entropy"] res = ui.prompt("Choose a feature selection algorithm:", options) switch = { 0: extract_ORB, 1: extract_SIFT, 2: extract_LBP, 3: extract_Gabor, 4: extract_Entropy, } fn = switch.get(int(res)) print("Should take less than {} minutes.".format(len(pageNames)*2)) print("Please wait...\n") # Run this with a pool of 3 agents until finished data = [] for pageName in pb.progressbar(pageNames): gc.collect() images = np.load(pageName) # for image in images: # data.append(fn(image)) with Pool(processes=3) as pool: if len(data) == 0: data = pool.map(fn, images, 16) else: data = np.concatenate((data, pool.map(fn, images, 16))) # Remove paged files (to clear up disk space) os.unlink(pageName) return data
def main(): gc.collect() # Garbage collect # Check arguments if len(sys.argv) < 2: return showUsage() ui.clear() # Pre-process PDFs dirname = sys.argv[1] images, targets, plotType = pproc.processPDFs(dirname) # Extract feature vectors (until user quits) doneExtracting = False while not doneExtracting: data, ftType = ft.extract_features(images) # Create, train, and evaluate model (until user quits) doneTraining = False while not doneTraining: tr.train(data, targets, plotType, ftType) options = ["Try another model", "Extract new features", "Quit"] res = ui.prompt(options=options) if options[int(res)] == "Quit": doneTraining = True doneExtracting = True elif options[int(res)] == "Extract new features": doneTraining = True gc.collect() # Garbage collect
def extract_features(images, vector_size=32): options = ["ORB", "SIFT", "LBP", "Gabor", "Entropy", "LBP and Entropy"] res = ui.prompt("Choose a feature selection algorithm:", options) type = options[int(res)] data = [] for img in pb.progressbar(images): # Process each image if type == "ORB": # Corner features alg = cv2.ORB_create() descriptor_size = 32 data.append( describe_keypoints(img, alg, vector_size, descriptor_size)) elif type == "SIFT": # Corner features (patented) alg = cv2.xfeatures2d.SIFT_create() descriptor_size = 128 data.append( describe_keypoints(img, alg, vector_size, descriptor_size)) elif type == "LBP": # Simple texture recognition alg = LocalBinaryPatterns(32, 16) grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) data.append(alg.describe(grey)) elif type == "Gabor": # prepare filter bank kernels kernels = [] for theta in range(4): theta = theta / 8. * np.pi for sigma in (1, 3): for frequency in (0.05, 0.25): kernel = np.real( gabor_kernel(frequency, theta=theta, sigma_x=sigma, sigma_y=sigma)) kernels.append(kernel) shrink = (slice(0, None, 3), slice(0, None, 3)) img_shrink = img_as_float(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))[shrink] feats = compute_feats(img_shrink, kernels).flatten() hist = exposure.histogram(img_shrink, nbins=16) data.append(np.append(feats, hist)) elif type == "Entropy": grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) grey = entropy(grey, disk(5)) hist = exposure.histogram(grey, nbins=16)[0] data.append(hist) elif type == "LBP and Entropy": grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) alg = LocalBinaryPatterns(32, 16) entropy_grey = entropy(grey, disk(5)) hist = exposure.histogram(entropy_grey, nbins=16)[0] data.append(np.append(alg.describe(grey), hist)) else: print("ERROR: Type " + type + " not found (features.extract_features())\n") return 1 return data, type
def numbQ(): global questions ui.echo("Number of questions, 1 - 25") questions = ui.prompt("Answer >") if ValNum(questions, 26): #om nummret ligger mellan 1-25 returneras true return questions #skickar tillbaka antalet frågor som ska finnas else: ui.echo("Invalid input, try again") ui.line() numbQ() #funktionen körs om ogiltigt svar kommer in
def numbOfQuestions(): global questions #gör en global variabel av questions för att vi använder den i och utanför funktionen ui.echo("Number of questions, 1 - 25") questions = ui.prompt("Answer >") if isValidNumber( questions, 26 ): #om nummret ligger mellan 1-25 returneras true från isValidNummer return questions #returnerar antalet frågor som ska finnas else: ui.echo("Invalid input, try again") ui.line() numbOfQuestions() #om ett ogiltigt svar anges körs funktionen om
def whatDiff(): #funktion för svårighetsgrad ui.header("Difficulty") ui.echo("1: Easy") ui.echo("2: Hard") difficulty = ui.prompt("Answer >") if difficulty == "1": APIget(easyAPI) #svar 1 ger lättare frågor elif difficulty == "2": APIget(hardAPI) #svar 2 ger svåra frågor else: ui.echo("Invalid input, try again") ui.line() whatDiff() #om något annat än 1 eller 2 anges så körs den om
def whatDifficulty(): #funktion för att välja svårighetsgrad ui.header("Difficulty") ui.echo("1: Easy") ui.echo("2: Hard") difficulty = ui.prompt("Answer >") if difficulty == "1": getApi(apiEasy) #om man svarar 1 så används apin med lättare frågor elif difficulty == "2": getApi(apiHard) #om man svarar 2 så används apin med svårare frågor else: ui.echo("Invalid input, try again") ui.line() whatDifficulty( ) #om något annat än 1 eller 2 anges så körsfunnktionen om
def main(): # Create images & extract features (until user quits) doneExtracting = False while not doneExtracting: pageNames, targets, filenames = pproc.process(sys.argv[1]) data = ft.features(pageNames) # Create and evaluate model (until user quits) doneTraining = False while not doneTraining: tr.train(data, targets, filenames) options = ["Try another model", "Extract new features", "Quit"] res = options[int(ui.prompt(options=options))] if res == "Quit": doneTraining = True doneExtracting = True elif res == "Extract new features": doneTraining = True
def process(directory): """Process each file in a directory, saving or loading images as directed""" files = [] options = ["Load", "Create"] choice = options[int(ui.prompt(options=options))] for item in os.listdir(directory): if os.path.isfile(os.path.join(directory, item)): filename = os.path.join(directory, item) if choice == "Load" and item.endswith(".png"): files.append(filename) elif choice == "Create" and item.endswith(".file"): files.append(filename) filenames, pageNames = imagePages(files, choice) targets = [name.split('/')[-1][:5] for name in filenames] return pageNames, targets, filenames
def imagePages(files, choice): """Pages images into npy file in groups of 100""" options = ["Byte", "Markov", "Hilbert"] type = options[int(ui.prompt("Choose a visualization type", options))] targets = [] pageNames = [] pageSize = 100 pages = range(math.ceil(len(files)/pageSize)) for page in pb.progressbar(pages): # print("\nPage {}/{}".format(page+1, len(pages))) gc.collect() # Garbage collect images = [] start = page*pageSize if choice == "Create": images, targets = buildImages(files[start:start+pageSize], targets, type) elif choice == "Load": images, targets = loadImages(files[start:start+pageSize], targets) pageNames.append("./pages/images_page{}.npy".format(page)) np.save(pageNames[-1], images) return targets, pageNames
def spell_check_this(): ui.clr() spell_check_menu = ui.Menu("Spell Check This™") spell_check_menu.display(False) print("\n") print("Word To Spell Check >> ") word = input() # normalize the input word = word.upper() if not DICTIONARY.is_word(word): print("\n") # spell check the word suggestions = suggest_correction(word) if ui.prompt("Verbose Logging?"): print("\n") print("DICTIONARY FORMAT (Suggested Word: Proximity Score):\n", "red") print(suggestions) print("\n\n") # print the suggestion with the lowest proximity score print("Suggestion: ") if suggestions: print(min(suggestions, key=suggestions.get), "green") else: print("None, word is garbled.") print("\n") else: print("\n") print("Input is a valid word!\n", "green")
import ui # importerar ui # använder funktioner från ui ui.line() # gör linje ui.header("EXEMPEL") # skriver ut i mitten och med | på sidorna ui.line(True) # gör linje av sjärnor ui.echo("Detta är ett exempel på hur") # skriver ut med en | från början ui.echo("ett grännsnitt kan se ut.") ui.line() ui.header("..vad vill du göra?") ui.line() ui.echo("A | Visa inköpslista") ui.echo("B | Lägg till vara") ui.echo("C | Ta bort vara") ui.echo("X | Stäng programmet") ui.line() ui.prompt("Val") # finns möjlighet att göra input
import ui # importerar ui och web import web # använder funktioner från ui ui.line() ui.header("ARTIST DATABASE") ui.line() ui.echo("Welcome to a world of") ui.echo("Musice!") ui.line() ui.echo(" L | List artists") ui.echo(" V | View artist profile") ui.echo(" E | Exit application") ui.line() s = ui.prompt("Selection") s # urlen går genom get funktionen från web url = "https://5hyqtreww2.execute-api.eu-north-1.amazonaws.com/artists/" r = web.get(url) # om man skriver in L if s == "L" or s == "l": ui.clear() ui.line() ui.header("ARTIST DATABASE") ui.line() ui.echo("Ariana Grande") ui.echo("Avicii") ui.echo("Blink -182") ui.echo("Brad Paisley") ui.echo("Ed Sheeran") ui.echo("Imagine Dragons") ui.echo("Maroon 5")
ui.header("Questions") numbQ() ui.line() while True: #frågesporten körs tills antalet frågor har uppnåtts, då stoppas den if count != int(questions): count += 1 #antalet gånger programmet har ställt en fråga, lägger till 1 när en ny fråga ställs NumbersGet() ui.echo(replace(QA[index]["fråga"])) #frågan ui.echo("Alternatives:") AltGet(index) #hämtar alternativ for i in alt: if i == QA[index]["correct"]: #om rätt svar correctAnsNum = integer #sparar det rätta värdets plats ui.echo(replace(str(integer) + ": " + i)) #skriver ut alternativen integer += 1 svar = ui.prompt("Answer >") if ValNum(svar, 5): #om svaret är mellan 1 och 4 if alt[int(svar) - 1] == alt[correctAnsNum - 1]: #om svaret är korrekt correctAns += 1 #lägger till ett poäng i minne outpttxt( "Your score: " + str(correctAns), "Correct! Your answer was " + str(correctAnsNum)) #anropar outpttxt som sätter fel/rätt integer = 1 else: outpttxt("Your score: " + str(correctAns), "Wrong! Correct answer was " + str(correctAnsNum)) integer = 1 else: outpttxt("Your score: " + str(correctAns),
def cmd_quit(self): if ui.prompt('Quit? [yn]', 'yn') == 'y': raise Quit() else: ui.new_ui_turn()
def main(): options = ["Threshold", "Select scanners"] type = options[int(ui.prompt(options=options))] dir = sys.argv[1] queue = [] data = [] targets = [] min_pos = [1, 0, None] max_neg = [0, 0, None] scans = {} for s in SCANNERS: scans[s] = [] # Report / scan each file for item in pb.progressbar(os.listdir(dir)): if item.endswith(".bmp") or item.endswith(".png"): continue filename = os.path.join(dir, item) file = open(filename, 'rb').read() hash = hashlib.sha256(file).hexdigest() res = report(hash) if res["response_code"] == 0: # File not found scan(filename, file) queue.append([filename, hash]) elif res["response_code"] == -2: # Scan in Queue queue.append([filename, hash]) elif res["response_code"] == 1: # File found targets.append(item[:5]) if type == "Threshold": data, max_neg, min_pos = thresholdReport( res, item, targets, data, max_neg, min_pos) elif type == "Select scanners": for s in SCANNERS: if s in res["scans"]: scans[s].append(not res["scans"][s]["detected"]) else: scans[s].append(False) # Check up on items in the queue while len(queue) > 0: print("Left in Queue: {}".format(len(queue))) for item in queue: res = report(item[1]) code = res["response_code"] if code == 0: # File not found print("ERROR: File {} not enqueued.".format(item[0])) elif code == 1: # File found targets.append(item[:5]) if type == "Threshold": data, max_neg, min_pos = thresholdReport( res, item, targets, data, max_neg, min_pos) elif type == "Select scanners": for s in SCANNERS: if s in res["scans"]: scans[s].append(not res["scans"][s]["detected"]) else: scans[s].append(False) queue.remove(item) if type == "Threshold": data = np.array(data) y_pred = data[:, 0] # Just first column of data[] y_true = [val == "CLEAN" for val in targets] # Set INFEC as positive val conf_matrix = skm.confusion_matrix(y_true, y_pred) accuracy = skm.accuracy_score(y_true, y_pred) precision = skm.precision_score(y_true, y_pred, average=None) recall = skm.recall_score(y_true, y_pred, average=None) f1 = skm.f1_score(y_true, y_pred, average=None) print("\n{}".format(conf_matrix)) print("Accuracy: {}".format(accuracy)) print("Precision: {}".format(precision[0])) print("Recall: {}".format(recall[0])) print("F1: {}".format(f1[0])) print("Max Negative: {}\nMin Positive: {}".format(max_neg, min_pos)) else: for s in SCANNERS: print("\nResults for {}:".format(s)) data = np.array(scans[s]) y_pred = data y_true = [val == "CLEAN" for val in targets] # Set INFEC as positive val conf_matrix = skm.confusion_matrix(y_true, y_pred) accuracy = skm.accuracy_score(y_true, y_pred) precision = skm.precision_score(y_true, y_pred, average=None) recall = skm.recall_score(y_true, y_pred, average=None) f1 = skm.f1_score(y_true, y_pred, average=None) print(conf_matrix) print("Accuracy: {}".format(accuracy)) print("Precision: {}".format(precision[0])) print("Recall: {}".format(recall[0])) print("F1: {}".format(f1[0]))
url = "https://5hyqtreww2.execute-api.eu-north-1.amazonaws.com/artists/" artists = web.get( "https://5hyqtreww2.execute-api.eu-north-1.amazonaws.com/artists/" )["artists"] #artists blir en variabel av svaret man får från apin som skickas till web.py och funktionen get ui.line() ui.header("ARTIST DB") ui.line() ui.echo("Welcome to a world of") ui.echo("Music!") ui.line() ui.echo(" L | List artists") ui.echo(" V | View artist profile") ui.echo(" E | Exit application") ui.line() selection = ui.prompt( "Selection >") #en input av användaret som bestämmer vad man vill göra while True: if selection.lower() == "l": #om inputen är l ui.line() ui.header("ARTIST DB") ui.line() for i in artists: #för varje plats i listan artists ui.echo(i["name"]) ui.line(True) ui.echo(" L | List artists") ui.echo(" V | View artist profile") ui.echo(" E | Exit application") ui.line() selection = ui.prompt( "Selection >") #tar in en ny input så att programmet kan fortsätta
artistsArr = requests.get(idUrl) artistJson = artistsArr.json()["artists"] for artist in artistJson: artists.append(artist["name"]) while True != False: ui.line(True) ui.header("Välkommen till artist-wiki") ui.line(True) nummer = 0 for art in artists: ui.echo(art + " ----- " + str(nummer)) nummer += 1 u_inp = ui.prompt( "Ange en artists nummer eller 'exit' om du vill avsluta programmet> ") if "exit" in u_inp.lower(): break else: try: a_artist = int(u_inp) ui.line() ui.echo("Du har valt " + artists[a_artist]) dinArtist = artistJson[a_artist]["id"] getIdUrl = idUrl + dinArtist artArr = requests.get(getIdUrl)
import ui #importerar ui.py ui.line() ui.header("Exempel") ui.line(True) ui.echo("Detta är ett exempel på hur") ui.echo("ett gränssnitt kan se ut") ui.line() ui.header("..vad vill du göra?") ui.line() ui.echo("A | Visa inköpslista") ui.echo("B | Lägg till vara") ui.echo("C | Ta bort vara ") ui.echo("X | Stäng programmet") ui.line() ui.prompt("Val") #anrop till funktioner i ui.py
import ui #importerar våra tidigare filer import web ui.line() ui.header("ARTIST DATABASE") ui.line() ui.echo("Welcome to a world of") ui.echo("Music!") ui.line() ui.echo("L", "List artists") ui.echo("V", "View artist profile") ui.echo("E", "Exit application") a = ui.prompt("Selection") running = "yes" #sätter någonting vi kan loopa med while running == "yes": b = web.get( "https://5hyqtreww2.execute-api.eu-north-1.amazonaws.com/artists/" ) #tidigare url:en, b kommer alltid att uppdateras när vi frågar efter information if a.title() == "L": #om valet är l eller L ui.line() ui.header("ARTIST DATABASE") ui.line() for x in b["artists"]: #för alla värden i artists ui.echo(x["name"] ) #letar den efter namn och skriver ut det som finns där ui.line(True) ui.echo("L", "List artists") ui.echo("V", "View artist profile") ui.echo("E", "Exit application")
def askStory(story): #if story type is already explained, go on #otherwise, explain #intro if not domain.getExplained(story.group): ui.tell(phrasebase.getReply("new_topic")) ui.tell(domain.groups[story.group]) answer = askForever(phrasebase.getReply("want_topic_explanation")) meaning = parsing.parse(answer) if meaning == "yes": ui.tell(domain.getExplanation(story.group)) domain.setExplained(story.group) ui.tell("Now let's get to the question!") if meaning == "no": ui.tell("Ok, then let's get right to the question.") ui.tell(story.text) ui.tell(story.question) ui.prompt() answer = ui.listenLong() meaning = parsing.parseQuiz(answer, story) # if answer == "": # ui.tell(phrasebase.getReply("offer_hint")) # ui.prompt() # answer = ui.listen() # meaning = parsing.parse(answer) # if meaning == "yes": # ui.tell(story.hint) # ui.prompt() # if meaning == "no": # ui.tell("ok!") # answer = askForever(phrasebase.getReply("introbla") + story.question) # meaning = parsing.parse(answer) if meaning == "whatquestion": ui.tell("The question was: " + story.question) # if meaning == "hint": # ui.tell(story.hint) # answer = askForever(phrasebase.getReply("introbla") + story.question) if meaning == "explain": ui.tell(phrasebase.getReply("offer_explanation")) ui.prompt() answer = ui.listen() meaning = parsing.parse(answer) if meaning == "yes": ui.tell(story.explain) #explained the answer #student model: didn't know the answer return if meaning == "no": ui.tell("ok!") answer = askForever(phrasebase.getReply("introbla") + story.question) meaning = parsing.parse(answer) if meaning == "correct": ui.tell(phrasebase.getReply("correct")) #student model: knew the answer elif meaning == "incorrect": ui.tell(phrasebase.getReply("incorrect")) ui.tell(phrasebase.getReply("offer_explanation")) ui.prompt() answer = ui.listen() meaning = parsing.parse(answer) if meaning == "yes": ui.tell(story.explain) #explained the answer #student model: didn't know the answer return
ui.line(False) # printar en linje gjord utav * ui.header("ARTIST DATABASE") ui.line(True) # printar en linje gjord utav - web.inspectart() #kallar på funktionen som tar fram informationen på specifika artister. ui.line(False) # printar en linje gjord utav * ui.echo("| Press enter to return ") # Printar våra val ui.line(False) # printar en linje gjord utav * ui.prompt() while True: #kör en stor while sålänge som end variabeln inte innehåller ui.clear() #Clear call ui.line(False) #printar en linje gjord utav - ui.header("Welcome to the Music Library") #printar en header ui.line(False)#printar en linje gjord utav - ui.line(False)#printar en linje gjord utav - ui.echo("| L | Lista alla Artister") #Printar våra val ui.echo("| V | Inspektera Artist ")#Printar våra val ui.echo("| E | Stäng av ") ui.line(False) choice = ui.prompt()#variable input så att du kan kalla på if choice == "L": #gör så att vi kan välja olika val alist() #kallar på functionen alist if choice == "V": #gör så att vi kan välja olika val. ainspect() #kallar på functionen ainspect if choice == "E": break