Spaces:
Paused
Paused
| import gradio as gr | |
| from sentence_transformers import SentenceTransformer | |
| from sklearn.metrics.pairwise import cosine_similarity | |
| import numpy as np | |
| from transformers import pipeline | |
| # doc set | |
| docs = [ | |
| "a python function is a reusable block of code. define one using 'def'. like: def greet(): print('hi')", | |
| "a for loop repeats code for each item in a list. like: for pet in pets: print(pet)", | |
| "a while loop repeats code while a condition is true. like: while x < 5: print(x); x += 1", | |
| "a variable stores a value. example: name = 'mei' stores the string 'mei' in the variable called name", | |
| "python is a programming language that's great for beginners. it’s used for everything from web apps to ai", | |
| "if statements let your code make choices. if it's raining: bring an umbrella! else: enjoy the sun", | |
| "import lets you pull in extra tools. like: import random lets you use random stuff in your code" | |
| ] | |
| # embed docs | |
| embedder = SentenceTransformer("all-MiniLM-L6-v2") | |
| doc_vectors = embedder.encode(docs) | |
| # use a Q&A pipeline instead of gen | |
| qa = pipeline("question-answering") | |
| def real_bot(message, history): | |
| # find closest doc | |
| q_vector = embedder.encode([message]) | |
| sims = cosine_similarity(q_vector, doc_vectors)[0] | |
| best_idx = np.argmax(sims) | |
| context = docs[best_idx] | |
| # use qa model to answer | |
| result = qa(question=message, context=context) | |
| answer = result["answer"] | |
| return answer | |
| # UI | |
| chat = gr.ChatInterface( | |
| fn = real_bot, | |
| title = "mei's python bot 🐍", | |
| description = "ask me python related questions, i’ll keep it short & sweet!" | |
| ) | |
| chat.launch() |