Spaces:
Paused
Paused
Download app.py from freelancerrhinobi/chatbot: direct link, hf CLI and curl.
- Browser
- Download file 9.81 kB
-
https://huggingface.co/spaces/freelancerrhinobi/chatbot/resolve/main/app.py
- Command line
-
hf download hf://spaces/freelancerrhinobi/chatbot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/freelancerrhinobi/chatbot/resolve/main/app.py
9.81 kB
| from fastapi import FastAPI, APIRouter | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel | |
| from datetime import datetime | |
| from typing import List | |
| from payments import create_checkout_session | |
| # Import adhd_gemini function from adhd_gemini module | |
| from gemini import gemini | |
| from user_info import user_info, update_user_by_userid | |
| from fastapi import FastAPI, Request, HTTPException | |
| import stripe | |
| from SessionHelper import * | |
| from chatgpt import chatgpt | |
| import os | |
| Ent_month=os.getenv('Ent_month') | |
| Ent_yearly=os.getenv('Ent_yearly') | |
| Prof_month=os.getenv('Prof_month') | |
| Prof_year=os.getenv('Prof_year') | |
| Base_month=os.getenv('Base_month') | |
| Base_year=os.getenv('Base_year') | |
| webhook_secret = os.getenv('webhook_secret') | |
| stripe.api_key = os.getenv('stripe_sk') | |
| # Create FastAPI app instance | |
| app = FastAPI() | |
| origins = [ | |
| "http://localhost:3000", # For local development | |
| os.getenv('firebase_url'), # Replace with your actual Firebase domain | |
| ] | |
| Assistants = { | |
| 'ADHD' :"Role : You are an virtual assistant who can help adhd patients. you will help them track activities and give emotional support", | |
| 'ResearchGPT' : 'Role: You are Researcher helping to uncover the insights. you help researchers summarize large data, assist in their academic works and much more.', | |
| 'HealthCare':"Role: You are a HealthCare analyst. You help customers related to healthcare. ", | |
| 'SalesAnalyst':'Role: You are a sales analyst consultant. based on the sales data given to you, you will analyze and tell customers about the sales insights.', | |
| 'MediConsultant':'Role: You are a medical consultant. you provide medical consultation to users. always mention that users should check with doctors if it is serious or can cause any emergency situations. ', | |
| 'DoctorGPT':'Role: you are doctor that to provide expert medical advice and information. Always caution user about going to doctor if it is serious case.', | |
| 'Resume':'''Role: you are Resume, | |
| a specialized version of LLM designed to assist with resume analysis and revision, | |
| job search based on resumes, and providing tips for tailoring resumes to specific job listings. | |
| you can help users refine their resume, and optimize their resume to better match job requirements''', | |
| 'Tutor':''' Role: you would be an AI guide designed to help students learn through the Socratic method. | |
| You would ask questions to guide their thinking, help them understand concepts, and encourage them to solve problems | |
| step-by-step without directly giving them the answers. | |
| You would also be kind, supportive, and patient, making sure students know that mistakes are part of learning. | |
| ''', | |
| 'Excel':"Role: You are Excel, the spcialise. you will help users with any query related to excel. problems related to forumla's different uses etc can be answered by you. you will answer only questions related to excel only. " | |
| } | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=origins, | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # Define a router for API documentation | |
| router = APIRouter() | |
| # Define request/response models | |
| class QueryIn(BaseModel): | |
| query: str | |
| userid:str | |
| usermail:str | |
| assistant:str | |
| class QueryOut(BaseModel): | |
| response: str | |
| class User(BaseModel): | |
| email: str | |
| userid:str | |
| membership:str | |
| isNewUser:bool | |
| chatgpt_tokens:int | |
| gemini_tokens:int | |
| last_accessed_date: datetime | |
| class QueryUser(BaseModel): | |
| userid:str | |
| usermail:str | |
| class PaymentIn(BaseModel): | |
| plan:str | |
| plantype:str | |
| userid:str | |
| class PaymentOut(BaseModel): | |
| url: str | |
| # Pydantic model for Stripe webhook event | |
| class StripeEventData(BaseModel): | |
| object: dict | |
| class StripeEvent(BaseModel): | |
| id: str | |
| object: str | |
| type: str | |
| data: StripeEventData | |
| # Pydantic model for webhook response | |
| class WebhookResponse(BaseModel): | |
| status: str = "success" | |
| async def stripe_webhook(request: Request): | |
| payload = await request.json() | |
| sig_header = request.headers.get("stripe-signature") | |
| try: | |
| # print('construting the data') | |
| event = stripe.Event.construct_from( | |
| payload, stripe.api_key | |
| ) | |
| # print('constructed the data') | |
| except ValueError as e: | |
| # Invalid payload | |
| print('invalid payload') | |
| raise HTTPException(status_code=400, detail="Invalid payload") | |
| except stripe.error.SignatureVerificationError as e: | |
| # print('Invalid signature | |
| raise HTTPException(status_code=400, detail="Invalid signature") | |
| # Handle the event | |
| # print("Received event:", event['type']) | |
| if event['type'] == 'checkout.session.completed': | |
| paid_status = event['data']['object']['payment_status'] | |
| session = event['data']['object'] | |
| amount = event['data']['object']['amount_total'] | |
| if paid_status == 'paid': | |
| # print("Payment was successful for session:", session['id']) | |
| update_membership(sessionID=session['id'],Amount=amount) | |
| else: | |
| print("payment failed for session ") | |
| # Perform additional logic, e.g., update order status in your database | |
| elif event['type'] == 'payment_intent.succeeded': | |
| # Handle other event types similarly | |
| pass | |
| return {"status": "success"} | |
| async def send_payment_url(q: PaymentIn): | |
| # Replace this with the actual URL you want to return | |
| # print(q.plan) | |
| # print(q.plantype) | |
| payment_url='' | |
| info = user_info(q.userid,"dummy") | |
| # print(info['membership']) | |
| if q.plantype=='Annually': | |
| if q.plan=='Base': | |
| payment_url=create_checkout_session(q.userid,Base_year) | |
| if q.plan=='Professional': | |
| payment_url=create_checkout_session(q.userid,Prof_year) | |
| if q.plan=='Enterprise': | |
| payment_url=create_checkout_session(q.userid,Ent_yearly) | |
| if q.plantype=='Monthly': | |
| if q.plan=='Base': | |
| payment_url=create_checkout_session(q.userid,Base_month) | |
| if q.plan=='Professional': | |
| payment_url=create_checkout_session(q.userid,Prof_month) | |
| if q.plan=='Enterprise': | |
| payment_url=create_checkout_session(q.userid,Ent_month) | |
| return PaymentOut(url=payment_url) | |
| # Define your endpoints | |
| async def get_user_info(q: QueryUser): | |
| """ | |
| Endpoint to receive a query and return the response. | |
| """ | |
| info = user_info(q.userid,q.usermail) | |
| # print(info) | |
| response = User(email=info['email'], | |
| userid = info['userid'], | |
| membership=info['membership'], | |
| isNewUser=info['isNewUser'], | |
| chatgpt_tokens=info['chatgpt_tokens'], | |
| gemini_tokens=info['gemini_tokens'], | |
| last_accessed_date= info['last_accessed_date'], | |
| ) | |
| return response | |
| async def gemini_func(q: QueryIn): | |
| """ | |
| Endpoint to receive a query and return the response. | |
| """ | |
| info = user_info(q.userid,q.usermail) | |
| # print('gemini inputs:') | |
| # print(q.query) | |
| if info: | |
| if info['gemini_tokens'] >0: | |
| if q.assistant in Assistants : | |
| query_final = Assistants[q.assistant]+'Query for the assistant: '+q.query | |
| # print(query_final) | |
| else: | |
| # print("select a assistant to be more beneficial") | |
| query_final=q.query | |
| response = gemini(query=query_final) | |
| info['gemini_tokens'] = info['gemini_tokens'] -1 | |
| update_user_by_userid(userid=q.userid,field_updates=info) | |
| return QueryOut(response=response) | |
| else: | |
| return QueryOut(response="Gemini tokens are over. upgrade to higher plan") | |
| return QueryOut(response="Error fetching data from database. contact Admin to resolve this") | |
| async def openai_func(q: QueryIn): | |
| """ | |
| Endpoint to receive a query and return the response. | |
| """ | |
| info = user_info(q.userid,q.usermail) | |
| # print('gemini inputs:') | |
| # print(q.query) | |
| if info: | |
| if info['chatgpt_tokens'] >0: | |
| if q.assistant in Assistants : | |
| query_final = Assistants[q.assistant]+'Query for the assistant: '+q.query | |
| # print(query_final) | |
| else: | |
| # print("select a assistant to be more beneficial") | |
| query_final=q.query | |
| response = chatgpt(query=query_final) | |
| info['chatgpt_tokens'] = info['chatgpt_tokens'] -1 | |
| update_user_by_userid(userid=q.userid,field_updates=info) | |
| return QueryOut(response=response) | |
| else: | |
| return QueryOut(response="ChatGPT tokens are over. upgrade to higher plan") | |
| return QueryOut(response="Error fetching data from database. contact Admin to resolve this") | |
| # Add a default endpoint to display available endpoints | |
| async def root(): | |
| return {"message": "Welcome to the chatbot API. Available endpoints:", | |
| "endpoints": [ | |
| "/adhd_gemini/ - POST method", | |
| "/adhd_openai/ - POST method" | |
| ]} | |
| # Include the router into the main app | |
| app.include_router(router) | |
| # Optionally, generate OpenAPI schema | |
| async def get_openapi(): | |
| return app.openapi() | |
| # This is optional, if you want to see the generated OpenAPI schema in Swagger UI | |
| async def get_docs(): | |
| return app.openapi_schema() | |
| # This is also optional, for using Redoc | |
| async def redoc(): | |
| return app.openapi_schema(url="/openapi.json") | |