#To accomplish this task you ll need to
1 messages · Page 1 of 1 (latest)
write the code for an interface that would allow users to create an account and create and update their bio and then search for other peoples bios using the semantic search
@half lantern from replit import db
from sentence_transformers import SentenceTransformer
from typing import List, Tuple
import numpy as np
def store_user(user_id: str, bio: str):
db[user_id] = bio
def get_all_users() -> List[Tuple[str, str]]:
return [(k, v) for k, v in db.items()]
def get_similarity_scores(user_id: str, model: SentenceTransformer) -> List[Tuple[str, float]]:
user_bio = db[user_id]
user_emb = model.encode([user_bio])
users = get_all_users()
users_emb = model.encode([bio for _, bio in users])
scores = np.inner(user_emb, users_emb)[0]
sorted_scores = sorted(zip([uid for uid, _ in users], scores), key=lambda x: x[1], reverse=True)
return sorted_scores
def match_users(user_id: str, n_matches: int = 1) -> List[str]:
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
user_matches = get_similarity_scores(user_id, model)
# Filter out the user's own ID and return top n_matches
return [uid for uid, score in user_matches if uid != user_id][:n_matches]
Store user ID and bios
store_user("user1", "I love hiking and exploring nature.")
store_user("user2", "Big fan of technology and video games.")
store_user("user3", "Sports enthusiast, especially basketball.")
store_user("user4", "I enjoy playing guitar and listening to rock music.")
Get best matches for a specific user
best_match = match_users("user1")
print("User 1's best match is:", best_match)
write the code for an interface that would allow users to create an account and create and update their bio and then search for other peoples bios using the semantic search
🤔 Thinking...
To create an interface, you can use Python Flask web framework and an HTML template to allow users to create an account, update their bio, and perform a semantic search for similar bios. Here's an example implementation for you:
Setup:
- Install Flask with
!pip install Flask. - Create two files:
app.pyand a folder calledtemplates. - Inside the
templatesfolder, create an HTML fileindex.html.
app.py:
from flask import Flask, render_template, request, redirect, url_for
from typing import List, Tuple
import numpy as np
from sentence_transformers import SentenceTransformer
from replit import db
app = Flask(__name__)
# Your existing functions from the previous implementation
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
user_id = request.form["user_id"]
bio = request.form["bio"]
action = request.form["action"]
if action == "create" or action == "update":
store_user(user_id, bio)
message = f"User '{user_id}' created/updated."
elif action == "search":
best_match = match_users(user_id)
message = f"User '{user_id}' best match is: {best_match}"
else:
message = "Invalid action."
return render_template("index.html", message=message)
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
templates/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Semantic Bio Search</title>
</head>
<body>
<h1>Semantic Bio Search</h1>
<form method="post">
<label for="user_id">User ID</label>
<input type="text" id="user_id" name="user_id" required><br><br>
<label for="bio">Bio</label>
<textarea id="bio" name="bio" rows="4" cols="50" required></
textarea><br><br>
<button type="submit" name="action" value="create">Create Account</button>
<button type="submit" name="action" value="update">Update Bio</button>
<button type="submit" name="action" value="search">Find Best Match</button>
</form>
{% if message %}
<p>{{ message }}</p>
{% endif %}
</body>
</html>
Now you can run the Flask app locally by entering `python app.py` in your terminal. The web interface will then be accessible at `http://127.0.0.1:5000/`. Users can create an account, update their bio or find the best match using the web interface.
Buy a NordVPN subscription and support @trentbot's continued operation. It's the safest way to browse online!
@half lantern write me a discord bot that has commands to change your bio and also a command to search for other people's bios using semantic search with huggingface model sentence-transformers/all-MiniLM-L6-v2
🤔 Thinking...
To create a Discord bot with the described functionalities, we first need to install the following libraries:
- Install discord.py with
!pip install discord.py. - Install transformers with
!pip install transformers. - Install torch if not installed with
!pip install torch.
Now, create a file named bot.py with the following content:
import os
import discord
from discord.ext import commands
from transformers import AutoTokenizer, AutoModel
import torch
import json
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
TOKEN = "YOUR-BOT-TOKEN"
bot = commands.Bot(command_prefix=">", intents=intents)
# Load the model and tokenizer
tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
model = AutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
user_bios = {}
@bot.event
async def on_ready():
print(f"{bot.user} has connected to Discord!")
@bot.command(name="bio", help="Changes your bio. Usage: >bio [new_bio]")
async def change_bio(ctx, *, new_bio: str):
user_id = str(ctx.author.id)
user_bios[user_id] = new_bio
await ctx.send(f"{ctx.author.mention}, your bio has been updated!")
@bot.command(name="search", help="Finds the closest matching bio. Usage: >search")
async def search(ctx):
user_id = str(ctx.author.id)
if user_id not in user_bios:
await ctx.send("Please set your bio with `>bio [your_bio]` before using the search command.")
return
# Calculate similarity scores
encoded_bios = tokenizer([bio for bio in user_bios.values()], padding=True, truncation=True, return_tensors='pt', max_length=128)
with torch.no_grad():
embeddings = model(**encoded_bios)[0].detach().numpy()
user_emb = embeddings[user_id]
scores = np.inner(user_emb, embeddings)
sorted_scores = sorted(zip(user_bios.keys(), scores), key=lambda x: x[1], reverse=True)
# Find best match excluding the user's ow