File size: 9,806 Bytes
6a3e5d3
a80b65f
f55e341
a80b65f
4ebae26
5d977c3
6a3e5d3
4ebae26
 
f8adb06
 
8890d40
071f216
838b113
 
 
 
 
 
 
 
 
60f471d
 
6a3e5d3
f55e341
a80b65f
 
726556a
a80b65f
4ebae26
 
 
 
 
 
 
7ba566f
 
 
 
 
 
 
 
770ccd0
071f216
4ebae26
a80b65f
 
 
 
 
 
 
6a3e5d3
 
 
 
f55e341
 
4ebae26
 
 
f55e341
 
 
a80b65f
1272f8d
a80b65f
 
 
 
 
 
 
 
 
5d977c3
 
 
 
 
 
 
 
 
 
d2b9b73
7a186f5
5f0cf93
 
 
7a186f5
 
5f0cf93
7a186f5
5f0cf93
7a186f5
 
 
 
 
25fbb78
 
d2b9b73
 
 
f8adb06
6ebe000
c002c7e
 
f8adb06
6ebe000
b701ae2
f8adb06
 
814b37b
f8adb06
 
d2b9b73
f8adb06
 
 
6ebe000
f8adb06
5f0cf93
8890d40
5f0cf93
a3a1d84
8890d40
6ebe000
a3a1d84
8890d40
6ebe000
f8adb06
5f0cf93
f8adb06
 
 
 
5d977c3
 
 
6ebe000
 
e9e17f3
5d977c3
6ebe000
e9e17f3
 
8890d40
e9e17f3
8890d40
e9e17f3
8890d40
e9e17f3
 
8890d40
e9e17f3
8890d40
e9e17f3
8890d40
5d977c3
 
 
 
6a3e5d3
a80b65f
 
 
 
 
 
4ebae26
a80b65f
 
 
 
 
 
 
a3a1d84
a80b65f
 
4ebae26
 
f55e341
 
 
4ebae26
 
 
 
 
 
 
60f471d
4ebae26
6ebe000
4ebae26
 
 
 
 
 
 
 
f55e341
4ebae26
 
f55e341
 
 
4ebae26
7ba566f
 
4ebae26
 
 
7ba566f
c95ef5d
4ebae26
6ebe000
4ebae26
071f216
4ebae26
 
 
 
 
 
6a3e5d3
 
 
 
06c48ce
6a3e5d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
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"

@app.post("/webhook")
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"}
@app.post("/payment_url/", response_model=PaymentOut)
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
@app.post("/user_info/", response_model=User)
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
@app.post("/gemini/", response_model=QueryOut)
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")

@app.post("/openai/", response_model=QueryOut)
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
@router.get("/")
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
@app.get("/openapi.json")
async def get_openapi():
    return app.openapi()

# This is optional, if you want to see the generated OpenAPI schema in Swagger UI
@app.get("/docs")
async def get_docs():
    return app.openapi_schema()

# This is also optional, for using Redoc
@app.get("/redoc")
async def redoc():
    return app.openapi_schema(url="/openapi.json")