Skip to content

Commit

Permalink
model updates to retrive the user previous recommendations
Browse files Browse the repository at this point in the history
  • Loading branch information
Hk669 committed Jul 22, 2024
1 parent 7149254 commit b09ac3f
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 5 deletions.
2 changes: 2 additions & 0 deletions src/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
RepositoryRecommendation,
get_user_collection,
append_recommendations_to_db,
get_user_previous_recommendations,
get_user_recommendation_by_id
# check_daily_limit
)
from .db import (
Expand Down
35 changes: 33 additions & 2 deletions src/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,27 @@
import os
import sys
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Header, Depends, Request
from fastapi import FastAPI, HTTPException, Header, Depends, Request, Query
from fastapi.middleware.cors import CORSMiddleware
from starlette.responses import RedirectResponse
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
import jwt
from datetime import timedelta, datetime
import uvicorn
from fastapi.responses import JSONResponse
from pymongo import MongoClient
from .user_data import get_repos
from src.db import (recommend,
get_topic_based_recommendations)
from src.models import User, GithubUser, get_user_collection, append_recommendations_to_db
from src.models import User, GithubUser, get_user_collection, append_recommendations_to_db, get_user_previous_recommendations, get_user_recommendation_by_id

# load_dotenv()
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)

client = MongoClient(os.environ['MONGODB_URL'])
db = client['github']

# console_handler = logging.StreamHandler(sys.stdout)
# console_handler.setLevel(logging.DEBUG)

Expand Down Expand Up @@ -241,6 +245,33 @@ async def get_recommendations(request: Request, current_user: dict = Depends(get
logger.error(f"Error: {str(e)}")
raise HTTPException(status_code=500, detail="An error occurred while generating recommendations")

@app.get('/api/user-recommendations')
async def get_user_recommendations(username: str = Query(...), current_user: dict = Depends(get_current_user)):
try:
if username != current_user["username"]:
raise HTTPException(status_code=403, detail="Unauthorized access")

user_recommendations = await get_user_previous_recommendations(username)
if not user_recommendations:
raise HTTPException(status_code=404, detail="No recommendations found for user")
return user_recommendations
except Exception as e:
logger.error(f"Error: {str(e)}")
raise HTTPException(status_code=500, detail="An error occurred while fetching user recommendations")


@app.get("/api/recommendation/{recommendation_id}")
async def get_recommendation_by_id(recommendation_id: str):
try:
recommendation = await get_user_recommendation_by_id(recommendation_id)
if not recommendation:
raise HTTPException(status_code=404, detail="Recommendation not found")
return recommendation
except Exception as e:
logger.error(f"Error: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))


@app.get('/api/health')
async def health_check(request: Request):
return JSONResponse({"status": "OK"})
Expand Down
28 changes: 25 additions & 3 deletions src/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import os
import uuid
import logging
import asyncio
from dotenv import load_dotenv
load_dotenv()

Expand Down Expand Up @@ -119,10 +120,10 @@ def append_recommendations_to_db(username, recommendations, recommendation_name)
raise ValueError("Failed to save user recommendations to DB")


def get_recommendation_by_id(recommendation_id):
async def get_user_recommendation_by_id(recommendation_id):
try:
recommendations_collection = db['recommendations']
recommendation_data = recommendations_collection.find_one({"recommendation_id": recommendation_id})
recommendation_data = await recommendations_collection.find_one({"recommendation_id": recommendation_id})

if not recommendation_data:
return None
Expand All @@ -137,6 +138,20 @@ def get_recommendation_by_id(recommendation_id):
raise ValueError("Failed to get recommendation from DB")


async def get_user_previous_recommendations(username: str) -> list:
try:
# Example query; adjust as per your database schema
user_recommendations = await db.user_recommendations.find_one({"username": username})
if not user_recommendations:
return []

# Assuming the recommendations are stored in 'recommendation_refs'
return user_recommendations.get("recommendation_refs", [])
except Exception as e:
logger.error(f"Database query error: {str(e)}")
raise


# TODO: v2
# def update_daily_limit_to_all_users():
# try:
Expand All @@ -159,4 +174,11 @@ def get_recommendation_by_id(recommendation_id):
# logger.warning(f"Daily limit exceeded for user: {username}")
# raise ValueError("Daily limit exceeded")

# return result
# return result

async def main():
recommendations = await get_user_previous_recommendations("Hk669")
print(recommendations)

if __name__ == "__main__":
asyncio.run(main())

0 comments on commit b09ac3f

Please sign in to comment.