Spaces:
Sleeping
Sleeping
File size: 13,180 Bytes
0dda2a1 c1fb41b 0dda2a1 c1fb41b 6c7d766 eff6080 7d859ca 0dda2a1 c4a2d1f b368e21 ba4a6fd 17050fe eff6080 c1fb41b eff6080 0dda2a1 b368e21 0dda2a1 76b93b0 b368e21 0dda2a1 8c0f543 ecf3a0b 8c0f543 c1fb41b 8c0f543 ecf3a0b ba4a6fd ecf3a0b ba4a6fd 0dda2a1 c1fb41b 8c0f543 0dda2a1 ba4a6fd 8c0f543 ba4a6fd 8c0f543 ba4a6fd 8c0f543 ba4a6fd 8c0f543 ba4a6fd 8c0f543 ba4a6fd 8c0f543 ba4a6fd 8c0f543 ba4a6fd 8c0f543 ba4a6fd 8c0f543 ba4a6fd ecf3a0b c1fb41b ba4a6fd 8c0f543 ba4a6fd 8c0f543 ba4a6fd c67130f ba4a6fd 0dda2a1 011040f b368e21 3fa5f95 b368e21 6febb6b 6187b6c 3fa5f95 8c0f543 b368e21 0dda2a1 6c7d766 40d15f0 0f88fd2 cfd2b5e 1945ea8 718d910 6c7d766 3fa5f95 b368e21 6c7d766 6187b6c 3fa5f95 b368e21 e25acc0 6c7d766 e6741bc 88d2fdc b368e21 e6741bc 88d2fdc 8f4f425 6c7d766 40d15f0 718d910 6c7d766 3fa5f95 6c7d766 3fa5f95 b368e21 6187b6c 3fa5f95 b368e21 e25acc0 6c7d766 7d859ca 718d910 7d859ca 3fa5f95 7d859ca 3fa5f95 b368e21 6187b6c 3fa5f95 b368e21 e25acc0 7d859ca 6c7d766 a383d87 17050fe 6c7d766 b368e21 17050fe 718d910 6c7d766 3fa5f95 6c7d766 3fa5f95 b368e21 6187b6c 3fa5f95 b368e21 17050fe 6c7d766 0dda2a1 b368e21 011040f 8f8a88e 681223f cfd2b5e 40d15f0 011040f 40d15f0 718d910 3fa5f95 064943c 40d15f0 b368e21 011040f 40d15f0 5ebc71d b368e21 6c7d766 5ebc71d 6c7d766 b368e21 6c7d766 718d910 6c7d766 3fa5f95 b368e21 ac9adab b9dd78c f4ddd80 ba4a6fd 937bcc4 d9c4277 53872bd b368e21 53872bd b368e21 53872bd 073e47f 53872bd 937bcc4 53872bd e25acc0 |
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 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 |
import io
from starlette import status
from functions import *
from PyPDF2 import PdfReader
import pandas as pd
from fastapi import FastAPI, File, UploadFile, HTTPException
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from langchain_community.document_loaders import UnstructuredURLLoader
from src.api.speech_api import speech_translator_router
from functions import client as supabase
from urllib.parse import urlparse
import nltk
nltk.download('punkt_tab')
app = FastAPI(title="ConversAI", root_path="/api/v1")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(speech_translator_router, prefix="/speech")
@app.post("/signup")
async def sign_up(email, username, password):
res, _ = supabase.auth.sign_up(
{"email": email, "password": password, "role": "user"}
)
user_id = res[1].id
r_ = createUser(user_id=user_id, username=username)
print(r_)
response = {
"status": "success",
"code": 200,
"message": "Please check you email address for email verification",
}
return response
@app.post("/session-check")
async def check_session():
res = supabase.auth.get_session()
return res
@app.post("/get-user")
async def get_user(access_token):
res = supabase.auth.get_user(jwt=access_token)
return res
@app.post("/referesh-token")
async def refresh_token(refresh_token):
res = supabase.auth.refresh_token(refresh_token)
return res
@app.post("/login")
async def sign_in(email, password):
try:
res = supabase.auth.sign_in_with_password(
{"email": email, "password": password}
)
user_id = res.user.id
access_token = res.session.access_token
refresh_token = res.session.refresh_token
store_session_check = supabase.table("Stores").select("*").filter("StoreID", "eq", user_id).execute()
store_id = None
if store_session_check and store_session_check.data:
store_id = store_session_check.data[0].get("StoreID")
if not store_id:
response = (
supabase.table("Stores").insert(
{
"AccessToken": access_token,
"StoreID": user_id,
"RefreshToken": refresh_token,
}
).execute()
)
message = {
"message": "Success",
"code": status.HTTP_200_OK,
"user_id": user_id,
"access_token": access_token,
"refresh_token": refresh_token
}
return message
elif store_id == user_id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="You are already signed in. Please sign out first to sign in again."
)
else:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Failed to sign in. Please check your credentials."
)
except HTTPException as http_exc:
raise http_exc
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"An unexpected error occurred during sign-in: {str(e)}"
)
@app.post('login_with_token')
async def login_with_token(token):
try:
res = supabase.auth.sign_in_with_id_token(token)
print(res)
user_id = res.user.id
access_token = res.session.access_token
refresh_token = res.session.refresh_token
store_session_check = supabase.table("Stores").select("*").filter("StoreID", "eq", user_id).execute()
store_id = None
if store_session_check and store_session_check.data:
store_id = store_session_check.data[0].get("StoreID")
if not store_id:
response = (
supabase.table("Stores").insert(
{
"AccessToken": access_token,
"StoreID": user_id,
"RefreshToken": refresh_token,
}
).execute()
)
message = {
"message": "Success",
"code": status.HTTP_200_OK,
"user_id": user_id,
"access_token": access_token,
"refresh_token": refresh_token
}
return message
elif store_id == user_id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="You are already signed in. Please sign out first to sign in again."
)
else:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Failed to sign in. Please check your credentials."
)
except HTTPException as http_exc:
raise http_exc
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"An unexpected error occurred during sign-in: {str(e)}"
)
@app.post("/set-session-data")
async def set_session_data(access_token, refresh_token):
res = supabase.auth.set_session(access_token, refresh_token)
return res
@app.post("/logout")
async def sign_out(user_id):
try:
supabase.table("Stores").delete().eq(
"StoreID", user_id
).execute()
res = supabase.auth.sign_out()
response = {"message": "success"}
return response
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@app.post("/oauth")
async def oauth(provider):
res = supabase.auth.sign_in_with_oauth({"provider": provider})
return res
@app.post("/newChatbot")
async def newChatbot(chatbotName: str, username: str):
currentBotCount = len(listTables(username=username)["output"])
limit = client.table("ConversAI_UserConfig").select("chatbotLimit").eq("user_id", username).execute().data[0][
"chatbotLimit"]
if currentBotCount >= int(limit):
return {
"output": "CHATBOT LIMIT EXCEEDED"
}
client.table("ConversAI_ChatbotInfo").insert({"user_id": username, "chatbotname": chatbotName}).execute()
chatbotName = f"convai${username}${chatbotName}"
return createTable(tablename=chatbotName)
@app.post("/addPDF")
async def addPDFData(vectorstore: str, pdf: UploadFile = File(...)):
source = pdf.filename
pdf = await pdf.read()
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as temp_file:
temp_file.write(pdf)
temp_file_path = temp_file.name
loader = PDFMinerLoader(file_path = temp_file_path, concatenate_pages = True)
text = loader.load()[0].page_content
os.remove(temp_file_path)
username, chatbotname = vectorstore.split("$")[1], vectorstore.split("$")[2]
df = pd.DataFrame(client.table("ConversAI_ChatbotInfo").select("*").execute().data)
currentCount = df[(df["user_id"] == username) & (df["chatbotname"] == chatbotname)]["charactercount"].iloc[0]
limit = client.table("ConversAI_UserConfig").select("tokenLimit").eq("user_id", username).execute().data[0][
"tokenLimit"]
newCount = currentCount + len(text)
if newCount < int(limit):
client.table("ConversAI_ChatbotInfo").update({"charactercount": str(newCount)}).eq("user_id", username).eq(
"chatbotname", chatbotname).execute()
return addDocuments(text=text, source=source, vectorstore=vectorstore)
else:
return {
"output": "DOCUMENT EXCEEDING LIMITS, PLEASE TRY WITH A SMALLER DOCUMENT."
}
@app.post("/scanAndReturnText")
async def returnText(pdf: UploadFile = File(...)):
pdf = await pdf.read()
text = getTextFromImagePDF(pdfBytes=pdf)
return text
@app.post("/addText")
async def addText(vectorstore: str, text: str):
username, chatbotname = vectorstore.split("$")[1], vectorstore.split("$")[2]
df = pd.DataFrame(client.table("ConversAI_ChatbotInfo").select("*").execute().data)
currentCount = df[(df["user_id"] == username) & (df["chatbotname"] == chatbotname)]["charactercount"].iloc[0]
newCount = currentCount + len(text)
limit = client.table("ConversAI_UserConfig").select("tokenLimit").eq("user_id", username).execute().data[0][
"tokenLimit"]
if newCount < int(limit):
client.table("ConversAI_ChatbotInfo").update({"charactercount": str(newCount)}).eq("user_id", username).eq(
"chatbotname", chatbotname).execute()
return addDocuments(text=text, source="text", vectorstore=vectorstore)
else:
return {
"output": "WEBSITE EXCEEDING LIMITS, PLEASE TRY WITH A SMALLER DOCUMENT."
}
class AddQAPair(BaseModel):
vectorstore: str
question: str
answer: str
@app.post("/addQAPair")
async def addText(addQaPair: AddQAPair):
username, chatbotname = addQaPair.vectorstore.split("$")[1], addQaPair.vectorstore.split("$")[2]
df = pd.DataFrame(client.table("ConversAI_ChatbotInfo").select("*").execute().data)
currentCount = df[(df["user_id"] == username) & (df["chatbotname"] == chatbotname)]["charactercount"].iloc[0]
qa = f"QUESTION: {addQaPair.question}\tANSWER: {addQaPair.answer}"
newCount = currentCount + len(qa)
limit = client.table("ConversAI_UserConfig").select("tokenLimit").eq("user_id", username).execute().data[0][
"tokenLimit"]
if newCount < int(limit):
client.table("ConversAI_ChatbotInfo").update({"charactercount": str(newCount)}).eq("user_id", username).eq(
"chatbotname", chatbotname).execute()
return addDocuments(text=qa, source="Q&A Pairs", vectorstore=addQaPair.vectorstore)
else:
return {
"output": "WEBSITE EXCEEDING LIMITS, PLEASE TRY WITH A SMALLER DOCUMENT."
}
@app.post("/addWebsite")
async def addWebsite(vectorstore: str, websiteUrls: list[str]):
loader = UnstructuredURLLoader(urls=websiteUrls)
docs = loader.load()
text = "\n\n".join(
[f"{docs[doc].page_content}" for doc in range(len(docs))]
)
username, chatbotname = vectorstore.split("$")[1], vectorstore.split("$")[2]
df = pd.DataFrame(client.table("ConversAI_ChatbotInfo").select("*").execute().data)
currentCount = df[(df["user_id"] == username) & (df["chatbotname"] == chatbotname)]["charactercount"].iloc[0]
newCount = currentCount + len(text)
limit = client.table("ConversAI_UserConfig").select("tokenLimit").eq("user_id", username).execute().data[0][
"tokenLimit"]
if newCount < int(limit):
client.table("ConversAI_ChatbotInfo").update({"charactercount": str(newCount)}).eq("user_id", username).eq(
"chatbotname", chatbotname).execute()
return addDocuments(text=text, source=urlparse(websiteUrls[0]).netloc, vectorstore=vectorstore)
else:
return {
"output": "WEBSITE EXCEEDING LIMITS, PLEASE TRY WITH A SMALLER DOCUMENT."
}
@app.post("/answerQuery")
async def answerQuestion(query: str, vectorstore: str, llmModel: str = "llama3-70b-8192"):
return answerQuery(query=query, vectorstore=vectorstore, llmModel=llmModel)
@app.post("/deleteChatbot")
async def delete(chatbotName: str):
username, chatbotName = chatbotName.split("$")[1], chatbotName.split("$")[2]
client.table('ConversAI_ChatbotInfo').delete().eq('user_id', username).eq('chatbotname', chatbotName).execute()
return deleteTable(tableName=chatbotName)
@app.post("/listChatbots")
async def delete(username: str):
return listTables(username=username)
@app.post("/getLinks")
async def crawlUrl(baseUrl: str):
return {
"urls": getLinks(url=baseUrl, timeout=30)
}
@app.post("/getCurrentCount")
async def getCount(vectorstore: str):
username, chatbotName = vectorstore.split("$")[1], vectorstore.split("$")[2]
df = pd.DataFrame(client.table("ConversAI_ChatbotInfo").select("*").execute().data)
return {
"currentCount": df[(df['user_id'] == username) & (df['chatbotname'] == chatbotName)]['charactercount'].iloc[0]
}
@app.post("/getYoutubeTranscript")
async def getYTTranscript(urls: str):
return {
"transcript": getTranscript(urls=urls)
}
@app.post("/analyzeData")
async def analyzeAndAnswer(query: str, file: UploadFile = File(...)):
extension = file.filename.split(".")[-1]
try:
if extension in ["xls", "xlsx", "xlsm", "xlsb"]:
df = pd.read_excel(io.BytesIO(await file.read()))
response = analyzeData(query=query, dataframe=df)
elif extension == "csv":
df = pd.read_csv(io.BytesIO(await file.read()))
response = analyzeData(query=query, dataframe=df)
else:
response = "INVALID FILE TYPE"
return {
"output": response
}
except:
return {
"output": "UNABLE TO ANSWER QUERY"
}
|