I am creating a content-based algorithm in python. I will use it to angular to make a recommendation, but every time I test it in postman it show
{
"error": "('count', None)"
}
Here's the code that I used. There's no problem with the connection with the supabase since I already check it and use debugger
from flask import Flask, jsonify, request
from supabase import create_client
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel
app = Flask(__name__)
supabase_url = 'this_is_for_url'
supabase_key = 'this_is_for_key'
supabase = create_client(supabase_url, supabase_key)
# Function to get recommendations based on clinic features
def get_recommendations(selected_clinic, df, cosine_sim):
# Get the index of the selected clinic
idx = df[df['cName'] == selected_clinic].index[0]
# Get the pairwise similarity scores of all clinics with that clinic
sim_scores = list(enumerate(cosine_sim[idx]))
# Sort the clinics based on the similarity scores
sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
# Get the scores of all similar clinics
sim_scores = sim_scores[1:2]
# Get the clinic indices
clinic_indices = [i[0] for i in sim_scores]
# Return the similar clinics
return df['cName'].iloc[clinic_indices].tolist()
# Custom tokenizer function
def custom_tokenizer(text):
return text.split()
@app.route('/api/recommendations', methods=['POST'])
def recommend():
try:
# Fetch data from Supabase
response, error = supabase.from_('clinic_tbl').select('*').execute()
# Check for errors or empty data
if error:
return jsonify({'error': str(error)})
if not response['data']:
return jsonify({'error': 'No clinics available'})
# Convert the Supabase response to a Pandas DataFrame
data = {
'cName': [],
'cService': [],
'cHealthcare': [],
'cSchedule': [],
}
for row in response['data']:
data['cName'].append(row.get('cName', ''))
data['cService'].append(row.get('cService', ''))
data['cHealthcare'].append(row.get('cHealthcare', ''))
data['cSchedule'].append(row.get('cSchedule', ''))
df = pd.DataFrame(data)
# Check if the DataFrame is empty
if df.empty:
return jsonify({'error': 'No clinics available'})
# Combine text features into a single string
df['content'] = df['cService'] + ' ' + df['cHealthcare'] + ' ' + df['cSchedule']
# Create a TF-IDF vectorizer with custom tokenizer
tfidf_vectorizer = TfidfVectorizer(tokenizer=custom_tokenizer, stop_words='english')
# Fit and transform the content into TF-IDF vectors
tfidf_matrix = tfidf_vectorizer.fit_transform(df['content'])
# Check if the vocabulary is not empty
if len(tfidf_vectorizer.vocabulary_) == 0:
return jsonify({'error': 'Empty vocabulary; perhaps the documents only contain stop words'})
# Calculate the cosine similarity between documents
cosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix)
# Get the selected clinic name from the request
selected_clinic_name = request.json.get('clinic_name', '')
# Get recommendations for the selected clinic
recommendations = get_recommendations(selected_clinic_name, df, cosine_sim)
return jsonify({'recommendations': recommendations})
except Exception as e:
return jsonify({'error': str(e)})
if __name__ == '__main__':
app.run(debug=True)
When I try to test it using csv file it doesn't encounter any error and shows the recommendation using postman.The code works. Here is the code
from flask import Flask, jsonify, request
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel
app = Flask(__name__)
# Function to get recommendations based on clinic features
def get_recommendations(selected_clinic, df, cosine_sim):
# Get the index of the selected clinic
idx = df[df['cName'] == selected_clinic].index[0]
# Get the pairwise similarity scores of all clinics with that clinic
sim_scores = list(enumerate(cosine_sim[idx]))
# Sort the clinics based on the similarity scores
sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
# Get the scores of all similar clinics
sim_scores = sim_scores[1:2]
# Get the clinic indices
clinic_indices = [i[0] for i in sim_scores]
# Return the similar clinics
return df['cName'].iloc[clinic_indices].tolist()
# Custom tokenizer function
def custom_tokenizer(text):
return text.split()
@app.route('/api/recommendations', methods=['POST'])
def recommend():
try:
# Load clinic data from CSV file
df = pd.read_csv('clinic_tbl.csv')
# Check for missing values
if df.isnull().values.any():
return jsonify({'error': 'Missing values in the dataset'})
# Check if the DataFrame is empty
if df.empty:
return jsonify({'error': 'No clinics available'})
# Combine text features into a single string
df['content'] = df['cService'] + ' ' + df['cHealthcare'] + ' ' + df['cSchedule']
# Create a TF-IDF vectorizer with custom tokenizer
tfidf_vectorizer = TfidfVectorizer(tokenizer=custom_tokenizer, stop_words='english')
# Fit and transform the content into TF-IDF vectors
tfidf_matrix = tfidf_vectorizer.fit_transform(df['content'])
# Check if the vocabulary is not empty
if len(tfidf_vectorizer.vocabulary_) == 0:
return jsonify({'error': 'Empty vocabulary; perhaps the documents only contain stop words'})
# Calculate the cosine similarity between documents
cosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix)
# Get the selected clinic name from the request
selected_clinic_name = request.json.get('clinic_name', '')
# Get recommendations for the selected clinic
recommendations = get_recommendations(selected_clinic_name, df, cosine_sim)
return jsonify({'recommendations': recommendations})
except Exception as e:
return jsonify({'error': str(e)})
if __name__ == '__main__':
app.run(debug=True)
can you help me find the problem with the first code
I want to fix the error issue