Spaces:
Running
Running
File size: 4,007 Bytes
8787f9d | 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 | from fastapi import FastAPI, Request, UploadFile, File
from fastapi.responses import JSONResponse, HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from langchain.chains import LLMChain
from langchain.vectorstores import Chroma
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.prompts import PromptTemplate
from langchain_groq import ChatGroq
from langchain.memory import VectorStoreRetrieverMemory
from pathlib import Path
import re
from io import BytesIO
from PyPDF2 import PdfReader
import docx
class GroqAIChatApp:
def __init__(self, api_key: str, persist_directory: str = "./chroma_db"):
self.embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
self.vectorstore = Chroma(persist_directory=persist_directory, embedding_function=self.embedding_model)
self.memory = VectorStoreRetrieverMemory(retriever=self.vectorstore.as_retriever())
self.llm = ChatGroq(api_key=api_key)
self.prompt_template = PromptTemplate(
input_variables=["history", "question"],
template="""You are an AI assistant. Use the context below to answer the question accurately.
Context:
{history}
Question: {question}
Answer:"""
)
self.conversation_chain = LLMChain(llm=self.llm, prompt=self.prompt_template, memory=self.memory)
def generate_response(self, question: str) -> str:
return self.conversation_chain.run({"question": question})
def process_file(self, file: UploadFile) -> str:
try:
if file.filename.endswith(".pdf"):
pdf_reader = PdfReader(BytesIO(file.file.read()))
text = "\n".join([page.extract_text() for page in pdf_reader.pages])
elif file.filename.endswith(".docx"):
doc = docx.Document(BytesIO(file.file.read()))
text = "\n".join([paragraph.text for paragraph in doc.paragraphs])
elif file.filename.endswith(".txt"):
text = file.file.read().decode("utf-8")
else:
raise ValueError("Unsupported file format")
text = re.sub(r'\s+', ' ', text)
return text
except Exception as e:
raise ValueError(f"Error processing file: {str(e)}")
def save_text_embeddings(self, text: str, metadata: dict):
try:
self.vectorstore.add_texts([text], metadatas=[metadata])
except Exception as e:
raise ValueError(f"Error saving embeddings: {str(e)}")
api_key = "your_groq_api_key" # Replace with your Groq API key
chat_app = GroqAIChatApp(api_key=api_key)
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/", response_class=HTMLResponse)
async def serve_frontend():
with open("static/index.html", "r") as file:
return HTMLResponse(content=file.read())
@app.post("/qa")
async def qa_endpoint(request: Request):
try:
data = await request.json()
question = data.get("question", "")
if not question:
return JSONResponse({"error": "No question provided."}, status_code=400)
answer = chat_app.generate_response(question)
return {"question": question, "answer": answer}
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=500)
@app.post("/upload")
async def upload_file(file: UploadFile = File(...)):
try:
text = chat_app.process_file(file)
metadata = {"filename": file.filename}
chat_app.save_text_embeddings(text, metadata)
return {"message": "File processed and embeddings saved successfully."}
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=500)
current_dir = Path(__file__).parent
app.mount("/static", StaticFiles(directory=current_dir / "static"), name="static")
|