MatchScore / app.py
TalalMosaik's picture
Update app.py
4958b7c verified
Raw History Blame Contribute Delete
7.52 kB
import streamlit as st
import faiss
import pandas as pd
import requests
import logging
import numpy as np
import requests
import logging
import time
index = faiss.read_index("faiss_index.index")
data = pd.read_csv("CleanListing2.csv")
system_prompt_images = '''
Imagine you are a top real estate agent and your task is to analyze properties according to the criteria defined by the client.
You will be provided with an input prompt and content as context that can be used to reply to the prompt.
The input prompt will contain 'Wants' and 'Needs'
'Wants' refers to features that must be strictly present in the property
'Needs' refers to features that are nice to have, but not strictly necessary
You will do the following things:
1. Find all properties that contains the 'Wants' and 'Needs' features
There will be three status that you can assign to each feature of a property; 'Full Match', 'Partial Match', 'No Match'
'Full Match': If the property contains all the 'Wants' and 'Needs' mentioned by the user
'Partial Match': If the property contains some of the 'Wants' and 'Needs' but there is possibility for other alternatives for example if the user has mentioned in the input 4 rooms and a Home office. You found a property that has 5 rooms but no home office explicitly mentioned. It would be a partial match for homeoffice, as the extra room can be converted to a home office
Use your thinking capabilities for the partial matches part
'No Match': If the property does not contain a 'Need' or 'Want' Feature
2. You will be calculating the total match score for each of the property that you return, it will be calculated such that a higher weight would be assigned to the 'Wants' feature as compared to the 'Needs' feature
Based on the total features found for 'Wants' or 'Needs' you will be assigning a total match score
You also need to add a reason why it is a 'Full Match' , 'Partial Match' , 'No Match' by referencing to the text you decided your decision on the matches
An example for the output is given for your reference
Property ID: 21213232424
Overall Match: 55%
- Wants
Bedroom: Full Match; Bedroom are mentioned in the property description of the rooms.
Flooring: Full Match; Flooring type is mentioned in the flooring description
Garage: No Match; No Garage is mentioned in the property description
- Needs
Balcony: Full Match; Balcony is mentioned in the outdoor space
Community Schools Nearby: No Match; No schools are mentioned for the schools category
Home Office: Partial Match; Although home office is not explicitly mentioned. However, there are 5 rooms mentioned out of which one can be converted to homeoffice
Property ID: 21213232423
Overall Match: 50%
- Wants
Bedroom: No Match; There is no bedroom mentioned in the property description
Flooring: Full Match; Flooring is explicitly found in the flooring field
Garage: No Match; No Garage is mentioned in the property outdoor
- Needs
Balcony: Balcony is mentioned in the outdoor space
Community Schools Nearby: Partial Match; There are no community schools explicitly mentioned but you can alternately use private school
You need to return all the properties with their respective matchscores
Please do not include any summary section
'''
#GPT 4o API Calling
GPT4V_KEY = "20d9adc17a0941768e28f1be2912eb0b"
GPT4V_ENDPOINT = "https://mosaik-resource-east-us-dev.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2024-02-15-preview"
headers = {
"Content-Type": "application/json",
"api-key": GPT4V_KEY,
}
def call_gpt4(question, context,system_prompt):
payload = {
"messages": [
{
"role": "system",
"content": system_prompt
},
{
"role": "user",
"content": f"Question: {question}\n\nContext: {context}"
}
],
"temperature": 0.5,
"top_p": 0.1,
"max_tokens": 2000
}
try:
response = requests.post(GPT4V_ENDPOINT, headers=headers, json=payload)
response.raise_for_status()
response_json = response.json()
logging.debug(f"Response JSON: {response_json}")
# Extracting the content and token usage from the response
if 'choices' in response_json and len(response_json['choices']) > 0:
content = response_json['choices'][0]['message']['content']
usage = response_json.get('usage', {})
return content, usage
else:
return "No valid response content found.", {}
except requests.RequestException as e:
logging.error(f"HTTP request failed: {e}")
return f"Error: {e}", {}
# Set up your API key and endpoint
EMBEDDING_KEY = "20d9adc17a0941768e28f1be2912eb0b"
EMBEDDING_ENDPOINT = "https://mosaik-resource-east-us-dev.openai.azure.com/openai/deployments/text-embedding-ada-002-v2/embeddings?api-version=2023-05-15"
headers = {
"Content-Type": "application/json",
"api-key": EMBEDDING_KEY,
}
# Define the create_embeddings function
def get_embeddings(text, endpoint, api_key):
headers = {
"Content-Type": "application/json",
"api-key": api_key,
}
embeddings = []
payload = {
"input": text
}
while True:
try:
response = requests.post(endpoint, headers=headers, json=payload)
response.raise_for_status()
response_json = response.json()
# logging.debug(f"Response JSON: {response_json}")
# embeddings.append(response_json['data'][0]['embedding'])
# if 'usage' in response_json:
# print("Tokens Used:")
# print(response_json['usage']['total_tokens'])
return(response_json['data'][0]['embedding'])
except requests.RequestException as e:
logging.error(f"HTTP request failed: {e}")
time.sleep(120)
# return embeddings
def generate_output(input_prompt, similar_content,system_prompt):
# Call the GPT-4 function with the constructed prompt
response, usage = call_gpt4(input_prompt, similar_content,system_prompt)
return response
# Define the function to be called when the submit button is clicked
def process(wish_list,system_prompt):
topk = 10
emb = get_embeddings(wish_list,EMBEDDING_ENDPOINT,EMBEDDING_KEY)
distances, indices = index.search(np.array(emb).reshape(1,-1),topk)
docs = data.iloc[indices[0]][['CleanData',"entry_id"]].values
listing_ids = data.iloc[indices[0]]['entry_id'].values
output = generate_output(input_prompt=wish_list,similar_content=docs,system_prompt=system_prompt)
return output, listing_ids
# Streamlit UI components
st.title("MatchScore App")
# Text fields for input
wish_list = st.text_area("Wish List")
system_prompt = st.text_area("Input Prompt",height=300,value=system_prompt_images)
# Submit button
if st.button("Submit"):
output, listing_ids = process(wish_list, system_prompt)
st.text_area("Output", value=output, height=400)
property_urls = ["https://app.mosaik.io/properties/search/listing-detail/195ac0a5771e8e64851e8764db5a52a0",'https://app.mosaik.io/properties/search/listing-detail/195ac0a5771e8e64851e8764db5a52a0']
st.write("### Property Links")
for prop_id in listing_ids:
st.markdown(f"Property: {prop_id} https://app.mosaik.io/properties/search/listing-detail/{prop_id}", unsafe_allow_html=True)