Spaces:
Sleeping
Sleeping
Commit ·
3742e69
1
Parent(s): 3a69823
final
Browse filesFiles changed (2)
- Dockerfile+2-5
- streamlit_app.py+10-46
123456 unmodified lines1213141516171819202 unmodified lines23242526# Use official lightweight Python imageFROM python:3.12.4-slim# Set environment variables to disable usage stats collection (to prevent write errors)ENV STREAMLIT_BROWSER_GATHERUSAGESTATS=false6 unmodified lines# Set working directoryWORKDIR /app# Create directory to store index with correct permissionsRUN mkdir -p /app/index && chmod -R 777 /app/index# Copy requirements and installCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt2 unmodified linesCOPY . .# Run the appCMD ["streamlit", "run", "streamlit_app.py", "--server.port=7860", "--server.enableXsrfProtection=false", "--server.enableCORS=false", "--server.address=0.0.0.0"]123456 unmodified lines1213141516172 unmodified lines20212223# Use official lightweight Python imageFROM python:3.10-slim# Set environment variables to disable usage stats collection (to prevent write errors)ENV STREAMLIT_BROWSER_GATHERUSAGESTATS=false6 unmodified lines# Set working directoryWORKDIR /app# Copy requirements and installCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt2 unmodified linesCOPY . .# Run the appCMD ["streamlit", "run", "streamlit_app.py", "--server.enableXsrfProtection=false", "--server.port=7860", "--server.address=0.0.0.0"]
9 unmodified lines101112131415161718192021222324252 unmodified lines28293031323334353637386 unmodified lines454647484950515253545556575859606162632 unmodified lines666768697071722 unmodified lines7576777879808182838485862 unmodified lines899091929394959697989910010110210310410510610716 unmodified lines12412512612712812913013113213313413513613713813914014114214314414514614714811 unmodified lines1601611621631641651661671681691701711721736 unmodified lines1801811821831841851861871881891901911929 unmodified linesfrom langchain.chains.question_answering import load_qa_chainfrom langchain.prompts import PromptTemplatefrom dotenv import load_dotenvimport logging# ========================# Logging Setup# ========================logging.basicConfig(level=logging.INFO,format="%(asctime)s [%(levelname)s] %(message)s")logger = logging.getLogger(__name__)# ========================# 1️⃣ Configuration2 unmodified linesload_dotenv()api_key = os.getenv("GOOGLE_API_KEY")if not api_key:logger.error("GOOGLE_API_KEY not found. Please add it to your .env file.")st.error("GOOGLE_API_KEY not found. Please add it to your .env file.")st.stop()logger.info("GOOGLE_API_KEY loaded successfully.")genai.configure(api_key=api_key)# ========================6 unmodified linestotal_size = 0for file in uploaded_files:size_mb = file.size / (1024 * 1024)logger.info(f"Checking file: {file.name}, size: {size_mb:.2f} MB")if size_mb > MAX_FILE_SIZE_MB:logger.warning(f"{file.name} is too large ({size_mb:.2f} MB). Limit is {MAX_FILE_SIZE_MB} MB per file.")st.warning(f"{file.name} is too large ({size_mb:.2f} MB). Limit is {MAX_FILE_SIZE_MB} MB per file.")return Falsetotal_size += size_mbif total_size > MAX_TOTAL_SIZE_MB:logger.warning(f"Total size of uploaded files is {total_size:.2f} MB. Limit is {MAX_TOTAL_SIZE_MB} MB in total.")st.warning(f"Total size of uploaded files is {total_size:.2f} MB. Limit is {MAX_TOTAL_SIZE_MB} MB in total.")return Falselogger.info("All file sizes are within limits.")return True# ========================2 unmodified linesdef get_pdf_text(pdf_docs):text = ""for pdf in pdf_docs:logger.info(f"Extracting text from PDF: {getattr(pdf, 'name', 'unknown')}")pdf_reader = PdfReader(pdf)for page in pdf_reader.pages:content = page.extract_text()2 unmodified linesreturn textdef get_docx_text(docx_file):logger.info(f"Extracting text from DOCX: {getattr(docx_file, 'name', 'unknown')}")doc = Document(docx_file)return "\n".join([para.text for para in doc.paragraphs])def get_html_text(html_file):logger.info(f"Extracting text from HTML: {getattr(html_file, 'name', 'unknown')}")content = html_file.read()soup = BeautifulSoup(content, "html.parser")return soup.get_text()2 unmodified lines# 4️⃣ Text Chunking and Vector Store# ========================def get_text_chunks(text):logger.info(f"Splitting text into chunks. Text length: {len(text)}")text_splitter = RecursiveCharacterTextSplitter(chunk_size=2000, chunk_overlap=200)return text_splitter.split_text(text)def get_vector_store(text_chunks):logger.info(f"Creating vector store with {len(text_chunks)} chunks.")embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)try:vector_store.save_local("/app/index/faiss_index")logger.info("Vector store saved to /app/index/faiss_index")except Exception as e:logger.error(f"Failed to save vector store: {e}")# ========================# 5️⃣ Conversational Chain Setup16 unmodified linesreturn chaindef user_input(user_question):logger.info(f"User question: {user_question}")embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")try:new_db = FAISS.load_local("/app/index/faiss_index", embeddings, allow_dangerous_deserialization=True)docs = new_db.similarity_search(user_question)logger.info(f"Found {len(docs)} similar documents.")except Exception as e:logger.error(f"Error loading vector store or searching: {e}")st.error(f"Error loading vector store or searching: {e}")returnchain = get_conversational_chain()try:response = chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)st.write("Reply:", response["output_text"])logger.info("Response generated successfully.")except Exception as e:logger.error(f"Error generating response: {e}")st.error(f"Error generating response: {e}")# ========================# 6️⃣ Streamlit App Layout11 unmodified linesst.title("Upload & Process Files")uploaded_files = st.file_uploader("Upload PDF, DOCX, or HTML files", accept_multiple_files=True, type=['pdf', 'docx', 'html'])if st.button("Submit & Process"):if not uploaded_files:logger.warning("No files uploaded.")st.warning("Please upload at least one file.")returnif not validate_file_sizes(uploaded_files):logger.warning("File size validation failed.")returnwith st.spinner("Processing files..."):6 unmodified lineselif file.name.endswith(".html"):full_text += get_html_text(file)else:logger.warning(f"Unsupported file type: {file.name}")st.warning(f"Unsupported file type: {file.name}")text_chunks = get_text_chunks(full_text)get_vector_store(text_chunks)st.success("Processing complete!")logger.info("Processing complete!")if __name__ == "__main__":main()9 unmodified lines1011121314152 unmodified lines1819202122232425266 unmodified lines3334353637383940414243444546472 unmodified lines5051525354552 unmodified lines585960616263646566672 unmodified lines7071727374757677787980818216 unmodified lines9910010110210310410510610710810911011111211311 unmodified lines1251261271281291301311321331341351361371381396 unmodified lines1461471481491501511521531541551569 unmodified linesfrom langchain.chains.question_answering import load_qa_chainfrom langchain.prompts import PromptTemplatefrom dotenv import load_dotenv# ========================# 1️⃣ Configuration2 unmodified linesload_dotenv()api_key = os.getenv("GOOGLE_API_KEY")if not api_key:st.error("GOOGLE_API_KEY not found. Please add it to your .env file.")st.stop()genai.configure(api_key=api_key)# ========================6 unmodified linestotal_size = 0for file in uploaded_files:size_mb = file.size / (1024 * 1024)if size_mb > MAX_FILE_SIZE_MB:st.warning(f"{file.name} is too large ({size_mb:.2f} MB). Limit is {MAX_FILE_SIZE_MB} MB per file.")return Falsetotal_size += size_mbif total_size > MAX_TOTAL_SIZE_MB:st.warning(f"Total size of uploaded files is {total_size:.2f} MB. Limit is {MAX_TOTAL_SIZE_MB} MB in total.")return Falsereturn True# ========================2 unmodified linesdef get_pdf_text(pdf_docs):text = ""for pdf in pdf_docs:pdf_reader = PdfReader(pdf)for page in pdf_reader.pages:content = page.extract_text()2 unmodified linesreturn textdef get_docx_text(docx_file):doc = Document(docx_file)return "\n".join([para.text for para in doc.paragraphs])def get_html_text(html_file):content = html_file.read()soup = BeautifulSoup(content, "html.parser")return soup.get_text()2 unmodified lines# 4️⃣ Text Chunking and Vector Store# ========================def get_text_chunks(text):text_splitter = RecursiveCharacterTextSplitter(chunk_size=2000, chunk_overlap=200)return text_splitter.split_text(text)def get_vector_store(text_chunks):embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)vector_store.save_local("faiss_index")# ========================# 5️⃣ Conversational Chain Setup16 unmodified linesreturn chaindef user_input(user_question):embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)docs = new_db.similarity_search(user_question)chain = get_conversational_chain()response = chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)st.write("Reply:", response["output_text"])# ========================# 6️⃣ Streamlit App Layout11 unmodified linesst.title("Upload & Process Files")uploaded_files = st.file_uploader("Upload PDF, DOCX, or HTML files", accept_multiple_files=True, type=['pdf', 'docx', 'html'])if st.button("Submit & Process"):if not uploaded_files:st.warning("Please upload at least one file.")returnif not validate_file_sizes(uploaded_files):returnwith st.spinner("Processing files..."):6 unmodified lineselif file.name.endswith(".html"):full_text += get_html_text(file)else:st.warning(f"Unsupported file type: {file.name}")text_chunks = get_text_chunks(full_text)get_vector_store(text_chunks)st.success("Processing complete!")if __name__ == "__main__":main()
Dockerfile+2-5
streamlit_app.py+10-46