Spaces:
Running
Running
Download app.py from MrTechie/TestingThinkAi: direct link, hf CLI and curl.
- Browser
- Download file 4.01 kB
-
https://huggingface.co/spaces/MrTechie/TestingThinkAi/resolve/main/app.py
- Command line
-
hf download hf://spaces/MrTechie/TestingThinkAi/app.py
-
curl -L -o app.py https://huggingface.co/spaces/MrTechie/TestingThinkAi/resolve/main/app.py
4.01 kB
| 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=["*"], | |
| ) | |
| async def serve_frontend(): | |
| with open("static/index.html", "r") as file: | |
| return HTMLResponse(content=file.read()) | |
| 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) | |
| 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") | |