File size: 4,214 Bytes
b21b232
 
 
 
 
86e971c
b21b232
 
86e971c
b21b232
86e971c
 
 
b21b232
 
 
 
 
 
 
 
 
86e971c
 
 
 
b21b232
 
 
 
 
 
 
 
 
 
 
 
 
86e971c
 
b21b232
 
 
86e971c
b21b232
 
 
 
 
 
 
 
 
 
 
 
 
 
8ebe686
b21b232
 
86e971c
b21b232
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86e971c
b21b232
 
 
86e971c
b21b232
 
 
 
 
 
 
8ebe686
b21b232
 
 
 
 
86e971c
b21b232
 
 
86e971c
b21b232
 
 
 
86e971c
b21b232
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# Import required libraries
from fastapi import FastAPI, HTTPException
#import redis
from dotenv import load_dotenv
import os
import torch

from modules.redistribute import redistribute, insert_element_at_position
#from modules.models.api import Input, Output, NewItem, UUID
from modules.database import BoostDatabase, UserDatabase, User
from _models.request import RankingRequest
from _models.response import RankingResponse, NewItem
from modules.models.api import UUID

# Load environment variables from .env file
load_dotenv('../.env')

# Access environment variables
redis_port = os.getenv("REDIS_PORT")
fastapi_port = os.getenv("FASTAPI_PORT")


print(f"Is CUDA available: {torch.cuda.is_available()}")
#print(f"CUDA device: {torch.cuda.get_device_name(torch.cuda.current_device())}")

#print("Redis port:", redis_port)
print("FastAPI port:", fastapi_port)

app = FastAPI()
boost_db = BoostDatabase('data/boost_bank.csv')
user_db = UserDatabase()


# Define a health check endpoint
@app.get("/")
async def health_check():
    return {"status": "ok"}

# Define FastAPI routes and logic
@app.post("/rank")
async def rerank_items(input_data: RankingRequest) -> RankingResponse:
    # who is the user?
    user = input_data.session.user_id
    date = input_data.session.current_time
    platform = input_data.session.platform
    items = input_data.items
    # TODO consider sampling them?

    print(items)
    reranked_ids, first_topic, insertion_pos = redistribute(items=items)
    #reranked_ids = [ for id_ in reranked_ids]
    print("here!")
    print(reranked_ids)

    user_in_db = user_db.get_user(user_id=user)

    # if user already exists -> has boosting records
    if user_in_db:
        # has been boosted today?
        print(user_in_db)
        if user_in_db.is_boosted_today():
            # return only reranked items, no insertion
            return RankingResponse(ranked_ids=reranked_ids, new_items=[])
        # user exists and not boosted today yet
        else:
            new_items = []
            boosts_received = user_in_db.boosts
            # there was some civic content in the batch
            if first_topic != "non-civic":
                fetched_boost = boost_db.get_random_boost(topic=first_topic,
                                                          platform=platform,
                                                          blacklist_ids=boosts_received)
                user_db.add_boost_to_user(user_id=user, boost=fetched_boost)
                user_db.update_user_boosted_today(user_id=user, date=date)
                
                # insert boost before first civic in batch
                reranked_ids = insert_element_at_position(lst=reranked_ids,
                                                          element=UUID(fetched_boost['id']),
                                                          position=insertion_pos)
                
                return RankingResponse(ranked_ids=reranked_ids, new_items=[NewItem(id=fetched_boost["id"], url=fetched_boost["url"])])

            # no civic content to boost on
            else:
                return RankingResponse(ranked_ids=reranked_ids, new_items=[])
    
    # user doesn't exist
    else:
        if first_topic != "non-civic":
            fetched_boost = boost_db.get_random_boost(topic=first_topic,
                                                    platform=platform,
                                                    blacklist_ids=[])

            user_db.add_user(user_id=user, 
                             user=User(user_id=user, last_boost=date, boosts=[fetched_boost]))
            
            # insert boost before first civic in batch
            reranked_ids = insert_element_at_position(lst=reranked_ids,
                                                    element=fetched_boost['id'],
                                                    position=insertion_pos)
            

            return RankingResponse(ranked_ids=reranked_ids, new_items=[NewItem(id=fetched_boost["id"], url=fetched_boost["url"])])

        # no civic content to boost on
        else:
            print("there")
            return RankingResponse(ranked_ids=reranked_ids, new_items=[])