Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,118 +1,115 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import shutil
|
| 3 |
-
from fastapi import FastAPI, UploadFile, File, HTTPException, Form
|
| 4 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 5 |
-
from pydantic import BaseModel
|
| 6 |
-
import requests
|
| 7 |
-
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 8 |
-
from langchain_community.vectorstores.faiss import FAISS
|
| 9 |
-
from langchain.chains.question_answering import load_qa_chain
|
| 10 |
-
from langchain.prompts import PromptTemplate
|
| 11 |
-
from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
|
| 12 |
-
import google.generativeai as genai
|
| 13 |
-
from dotenv import load_dotenv
|
| 14 |
-
|
| 15 |
-
app = FastAPI()
|
| 16 |
-
|
| 17 |
-
# Configure CORS
|
| 18 |
-
app.add_middleware(
|
| 19 |
-
CORSMiddleware,
|
| 20 |
-
allow_origins=["*"],
|
| 21 |
-
allow_credentials=True,
|
| 22 |
-
allow_methods=["*"],
|
| 23 |
-
allow_headers=["*"],
|
| 24 |
-
)
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
class
|
| 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 |
-
except
|
| 80 |
-
print(f"
|
| 81 |
-
raise
|
| 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 |
-
# Context: \n {context}?\n
|
| 116 |
-
# Question: \n {question}\n
|
| 117 |
-
# Answer:
|
| 118 |
# """
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import shutil
|
| 3 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException, Form
|
| 4 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 5 |
+
from pydantic import BaseModel
|
| 6 |
+
import requests
|
| 7 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 8 |
+
from langchain_community.vectorstores.faiss import FAISS
|
| 9 |
+
from langchain.chains.question_answering import load_qa_chain
|
| 10 |
+
from langchain.prompts import PromptTemplate
|
| 11 |
+
from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
|
| 12 |
+
import google.generativeai as genai
|
| 13 |
+
from dotenv import load_dotenv
|
| 14 |
+
|
| 15 |
+
app = FastAPI()
|
| 16 |
+
|
| 17 |
+
# Configure CORS
|
| 18 |
+
app.add_middleware(
|
| 19 |
+
CORSMiddleware,
|
| 20 |
+
allow_origins=["*"],
|
| 21 |
+
allow_credentials=True,
|
| 22 |
+
allow_methods=["*"],
|
| 23 |
+
allow_headers=["*"],
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
load_dotenv()
|
| 27 |
+
genai.configure(api_key="AIzaSyCCIYW0HamEfEMyGMXhQypyYtiY4O2ixUg")
|
| 28 |
+
|
| 29 |
+
class QuestionInput(BaseModel):
|
| 30 |
+
question: str
|
| 31 |
+
|
| 32 |
+
class UploadInput(BaseModel):
|
| 33 |
+
url: str = Form(None)
|
| 34 |
+
|
| 35 |
+
def scrape_data(url):
|
| 36 |
+
|
| 37 |
+
return "scraped data"
|
| 38 |
+
|
| 39 |
+
def split_text_into_chunks(text):
|
| 40 |
+
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
| 41 |
+
text_chunks = splitter.split_text(text)
|
| 42 |
+
return text_chunks
|
| 43 |
+
|
| 44 |
+
def create_vector_store(chunks):
|
| 45 |
+
embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
|
| 46 |
+
vector_store = FAISS.from_texts(chunks, embedding=embeddings)
|
| 47 |
+
vector_store.save_local("faiss_index")
|
| 48 |
+
|
| 49 |
+
def setup_conversation_chain(template):
|
| 50 |
+
model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
|
| 51 |
+
prompt = PromptTemplate(template=template, input_variables=["context", "question"])
|
| 52 |
+
chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
|
| 53 |
+
return chain
|
| 54 |
+
|
| 55 |
+
@app.post("/upload")
|
| 56 |
+
async def upload_files(url: str = Form(None)):
|
| 57 |
+
try:
|
| 58 |
+
# print(url)
|
| 59 |
+
# all_text = ""
|
| 60 |
+
|
| 61 |
+
# # Process URL
|
| 62 |
+
# if url:
|
| 63 |
+
# # check if url is valid (request doesnt give error)
|
| 64 |
+
# if # doesnt give error
|
| 65 |
+
# all_text = scrape_data(url)
|
| 66 |
+
# else:
|
| 67 |
+
# raise HTTPException(status_code=400, detail="Invalid URL")
|
| 68 |
+
|
| 69 |
+
# if not all_text:
|
| 70 |
+
# raise HTTPException(status_code=400, detail="No content to process")
|
| 71 |
+
|
| 72 |
+
# chunks = split_text_into_chunks(all_text)
|
| 73 |
+
# create_vector_store(chunks)
|
| 74 |
+
|
| 75 |
+
return {"message": "Content uploaded and processed successfully"}
|
| 76 |
+
except HTTPException as http_exc:
|
| 77 |
+
print(f"HTTP Exception: {http_exc.detail}")
|
| 78 |
+
raise http_exc
|
| 79 |
+
except Exception as e:
|
| 80 |
+
print(f"Unhandled Exception: {e}")
|
| 81 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@app.post("/ask")
|
| 85 |
+
async def ask_question(question_input: QuestionInput):
|
| 86 |
+
try:
|
| 87 |
+
embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
|
| 88 |
+
indexed_data = FAISS.load_local("reviews_index", embeddings, allow_dangerous_deserialization=True)
|
| 89 |
+
docs = indexed_data.similarity_search(question_input.question)
|
| 90 |
+
|
| 91 |
+
prompt_template = """
|
| 92 |
+
Your alias is AI Rate Professor. Your task is to provide a thorough response based on the given context, ensuring all relevant details are included.
|
| 93 |
+
If the requested information isn't available, simply state, "answer not available in context," then answer based on your understanding, connecting with the context.
|
| 94 |
+
Don't provide incorrect information.\n\n
|
| 95 |
+
Context: \n {context}?\n
|
| 96 |
+
Question: \n {question}\n
|
| 97 |
+
Answer:
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
chain = setup_conversation_chain(prompt_template)
|
| 101 |
+
response = chain({"input_documents": docs, "question": question_input.question}, return_only_outputs=True)
|
| 102 |
+
|
| 103 |
+
print(response["output_text"])
|
| 104 |
+
return {"answer": response["output_text"]}
|
| 105 |
+
except Exception as e:
|
| 106 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 107 |
+
|
| 108 |
+
# prompt_template = """
|
| 109 |
+
# Your alias is AI Rate Professor. Your task is to provide a thorough response based on the given context, ensuring all relevant details are included.
|
| 110 |
+
# If the requested information isn't available, simply state, "answer not available in context," then answer based on your understanding, connecting with the context.
|
| 111 |
+
# Don't provide incorrect information.\n\n
|
| 112 |
+
# Context: \n {context}?\n
|
| 113 |
+
# Question: \n {question}\n
|
| 114 |
+
# Answer:
|
|
|
|
|
|
|
|
|
|
| 115 |
# """
|