Skip to content

Commit

Permalink
refactor: Implement lazy loading for images in DashboardV2 and update…
Browse files Browse the repository at this point in the history
… chat route
  • Loading branch information
Arghya721 committed Jul 14, 2024
1 parent 21dc108 commit ddff4a8
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 37 deletions.
38 changes: 30 additions & 8 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -510,7 +510,7 @@ async def chat_event_streaming(request: ChatRequest, token_info: dict = Depends(
if not chat_config:
raise ValueError(f"Invalid chat model: {chat_model}")

if chat_config['premium'] == True:
if chat_config['premium']:
if not verify_active_subscription(token_info):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
Expand Down Expand Up @@ -619,18 +619,22 @@ async def chat_title(request: ChatRequest, token_info: dict = Depends(verify_tok
try:
# Get the chat model from the request and create the corresponding chat instance
chat_model = request.chat_model
chat = model_company_mapping.get(chat_model)
if chat is None:
chat_config = model_company_mapping.get(chat_model)

if not chat_config:
raise ValueError(f"Invalid chat model: {chat_model}")

print("Chat model: ", chat_model)

if chat_config['premium']:
if not verify_active_subscription(token_info):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Forbidden",
)

# Create the chat prompt and memory for the conversation
chat = chat(
chat = chat_config['model'](
model_name=chat_model,
model=chat_model,
temperature=0,
temperature=request.temperature,
)


Expand Down Expand Up @@ -822,6 +826,24 @@ async def get_plans(token_info: dict = Depends(verify_token)):
logging.error("Error getting plans: %s", e)
raise HTTPException(status_code=500, detail="Internal server error") from e

@app.get("/v1/is_user_subscribed", tags=["Subscription Endpoints"])
async def is_user_subscribed(token_info: dict = Depends(verify_token)):
"""Check if the user is subscribed."""
try:
# check if the customer has a subscription
subscription_ref = db.collection('subscriptions').where('customer_id', '==', token_info['sub']).stream()

# check if the customer has an active subscription
for doc in subscription_ref:
subscription_data = doc.to_dict()
subscription_status = subscription.fetch(subscription_data['subscription_id'])['status']
if subscription_status == 'active':
return {"subscribed": True}

return {"subscribed": False}
except Exception as e:
logging.error("Error checking if user is subscribed: %s", e)
raise HTTPException(status_code=500, detail="Internal server error") from e

if __name__ == "__main__":
import uvicorn
Expand Down
54 changes: 27 additions & 27 deletions web/src/options/modelOptions.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

38 changes: 36 additions & 2 deletions web/src/pages/DashboardV2.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import loading from '../images/loading.webp';
import { AiOutlineReload } from 'react-icons/ai';
import LoadingSpinner from '../components/LoadingSpinner';
import { PlansModal } from "../components/PlansModal";
import { Chip } from "@nextui-org/react";

export const DashboardV2 = () => {
const { chatIdParams } = useParams();
Expand All @@ -46,6 +47,7 @@ export const DashboardV2 = () => {
const [isRequestFailed, setIsRequestFailed] = useState(false); // New state for request failed
const chatWindowRef = useRef(null);
const { isOpen, onOpen, onClose } = useDisclosure();
const [isPlusSubscriber, setIsPlusSubscriber] = useState(false);

const limitSentence = (sentence) => {
// limit chat title to 30 characters
Expand Down Expand Up @@ -338,6 +340,29 @@ export const DashboardV2 = () => {
}
}, [chatIdParams]);

useEffect(() => {
// check if the user has a plus plan
const hasPlusSubscription = async () => {
try {
const response = await fetch(`${API_HOST}/v1/is_user_subscribed`, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});

if (response.ok) {
const data = await response.json();
setIsPlusSubscriber(data.subscribed);
console.log('User has Plus subscription:', data.subscribed);
}

} catch (error) {
console.error('Error fetching subscription status:', error);
}
}
hasPlusSubscription();
}, [accessToken]);

return (
<div className="grid grid-cols-12 h-screen dark:bg-zinc-900">
{/* Sidebar */}
Expand Down Expand Up @@ -467,8 +492,16 @@ export const DashboardV2 = () => {
<Select
className="w-52 md:w-full ml-4"
selectedKeys={[selectedModel?.value]}
onChange={(event) =>
setSelectedModel(modelOptions.find((model) => model.value === event.target.value))
onChange={(event) => {
// check for plus subscription
let selectedModel = modelOptions.find((model) => model.value === event.target.value);
if (selectedModel.isPremium && !isPlusSubscriber) {
setModal('plans');
onOpen();
} else {
setSelectedModel(selectedModel)
}
}
}
label="Select model"
startContent={selectedModel?.companyLogo}
Expand All @@ -478,6 +511,7 @@ export const DashboardV2 = () => {
key={model.value}
className="max-w-xs"
startContent={model.companyLogo}
endContent={model.isPremium ? <Chip color="primary" size="sm">Plus</Chip> : null}
>
{model.label}
</SelectItem>
Expand Down

0 comments on commit ddff4a8

Please sign in to comment.