Spaces:
Build error
Build error
Update app.py
Browse files11 unmodified lines12131415161718192021222324252627282 unmodified lines31323334353637383940414243446 unmodified lines515253545556575859606162631 unmodified line6566676869707172736 unmodified lines80818283848586878889909192939495969798991001011021031041051068 unmodified lines11511611711811912012111 unmodified linesfrom langchain.chains import RetrievalQAfrom langchain_groq import ChatGroqclass ChatbotModel:def __init__(self):os.environ["GROQ_API_KEY"] = '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'self.embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2",model_kwargs={'device': 'cpu'},encode_kwargs={'normalize_embeddings': True})self.llm = ChatGroq(model='llama3-70b-8192',temperature=0.5,2 unmodified linesmax_retries=2,)self.memory = ConversationBufferMemory(memory_key="history", input_key="question")self.template = """You are an intelligent assistant... (Rest of your prompt as is)"""self.QA_CHAIN_PROMPT = PromptTemplate(input_variables=["history", "context", "question"],template=self.template)self.db1 = Noneself.qa_chain = None6 unmodified linesreturn "\n".join([pytesseract.image_to_string(img, lang=language) for img in images])def process_file(self, uploaded_file):_, file_extension = os.path.splitext(uploaded_file.name)file_extension = file_extension.lower()with tempfile.NamedTemporaryFile(delete=False, suffix=file_extension) as temp_file:temp_file.write(uploaded_file.read())temp_path = temp_file.nameif file_extension == '.pdf':raw_text = self.ocr_pdf(temp_path, language='guj+eng')elif file_extension in ['.jpg', '.jpeg', '.png', '.bmp']:1 unmodified lineelse:return "Unsupported file format."text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)text_chunks = text_splitter.split_text(raw_text)self.db1 = FAISS.from_documents(text_chunks, self.embeddings)self.qa_chain = RetrievalQA.from_chain_type(self.llm,6 unmodified lines"memory": self.memory})return "File processed successfully!"def get_response(self, user_input):if not self.qa_chain:return "Please upload and process a file before asking questions."response = self.qa_chain({"query": user_input})return response["result"]chatbot = ChatbotModel()def upload_and_process(file):return chatbot.process_file(file)def ask_question(question):return chatbot.get_response(question)interface = gr.Blocks()with interface:8 unmodified linesask_btn = gr.Button("Submit")answer = gr.Textbox(label="Answer")upload_btn.click(upload_and_process, inputs=file_upload, outputs=output)ask_btn.click(ask_question, inputs=question_box, outputs=answer)interface.launch()11 unmodified lines121314151617181920212223242526272829302 unmodified lines333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011026 unmodified lines1091101111121131141151161171181191201211221231241 unmodified line1261271281291301311321331341351366 unmodified lines1431441451461471481491501511521531541551561571581591601611621631641651661671688 unmodified lines17717817918018118218318418511 unmodified linesfrom langchain.chains import RetrievalQAfrom langchain_groq import ChatGroqclass ChatbotModel:def __init__(self):# Initialize the environment variable for the GROQ API Keyos.environ["GROQ_API_KEY"] = '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'# Initialize embeddingsself.embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2",model_kwargs={'device': 'cpu'},encode_kwargs={'normalize_embeddings': True})# Initialize the chat modelself.llm = ChatGroq(model='llama3-70b-8192',temperature=0.5,2 unmodified linesmax_retries=2,)# Initialize memory for conversationself.memory = ConversationBufferMemory(memory_key="history", input_key="question")# Create the QA chain prompt templateself.template = """You are an intelligent educational assistant specialized in handling queries about documents in both English and Gujarati languages. You have been provided with OCR-processed text from {document_type} that contains important educational information.Core Responsibilities:1. Language Processing:- Identify the language of the user's query (English or Gujarati)- Respond in the same language as the query- If the query is in Gujarati, ensure the response maintains proper Gujarati grammar and terminology- For technical terms, provide both English and Gujarati versions when relevant2. Document Understanding:- Analyze the OCR-processed text from the uploaded {document_type}- Account for potential OCR errors or misinterpretations- Focus on extracting accurate information despite possible OCR imperfections3. Response Guidelines:- Provide direct, clear answers based solely on the document content- If information is unclear due to OCR quality, mention this limitation- For numerical data (dates, percentages, marks), double-check accuracy before responding- If information is not found in the document, clearly state: "This information is not present in the uploaded document"4. Educational Context:- Maintain focus on educational queries related to the document content- For admission-related queries, emphasize important deadlines and requirements- For scholarship information, highlight eligibility criteria and application processes- For course-related queries, provide detailed, accurate information from the document5. Response Format:- Structure responses clearly with relevant subpoints when necessary- For complex information, break down the answer into digestible parts- Include relevant reference points from the document when applicable- Format numerical data and dates clearly6. Quality Control:- Verify that responses align with the document content- Don't make assumptions beyond the provided information- If multiple interpretations are possible due to OCR quality, mention all possibilities- Maintain consistency in terminology throughout the conversationImportant Rules:- Never make up information not present in the document- Don't combine information from previous conversations or external knowledge- Always indicate if certain parts of the document are unclear due to OCR quality- Maintain professional tone while being accessible to students and parents- If the query is out of scope of the uploaded document, politely redirect to relevant official sourcesContext from uploaded document:{context}Chat History:{history}Current Question: {question}Assistant: Let me provide a clear and accurate response based on the uploaded document content..."""self.QA_CHAIN_PROMPT = PromptTemplate(input_variables=["history", "context", "question"],template=self.template)self.db1 = Noneself.qa_chain = None6 unmodified linesreturn "\n".join([pytesseract.image_to_string(img, lang=language) for img in images])def process_file(self, uploaded_file):"""Process an uploaded file and initialize the QA chain."""_, file_extension = os.path.splitext(uploaded_file.name)file_extension = file_extension.lower()# Temporarily save the file for processingwith tempfile.NamedTemporaryFile(delete=False, suffix=file_extension) as temp_file:temp_file.write(uploaded_file.read())temp_path = temp_file.name# OCR processing based on file typeif file_extension == '.pdf':raw_text = self.ocr_pdf(temp_path, language='guj+eng')elif file_extension in ['.jpg', '.jpeg', '.png', '.bmp']:1 unmodified lineelse:return "Unsupported file format."# Split text into chunkstext_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)text_chunks = text_splitter.split_text(raw_text)# Create vector store and initialize QA chainself.db1 = FAISS.from_documents(text_chunks, self.embeddings)self.qa_chain = RetrievalQA.from_chain_type(self.llm,6 unmodified lines"memory": self.memory})return "File processed successfully!"def get_response(self, user_input):"""Generate response to the user input question."""if not self.qa_chain:return "Please upload and process a file before asking questions."response = self.qa_chain({"query": user_input})return response["result"]# Initialize the chatbotchatbot = ChatbotModel()# Define Gradio interface functionsdef upload_and_process(file):return chatbot.process_file(file)def ask_question(question):return chatbot.get_response(question)# Set up Gradio interfaceinterface = gr.Blocks()with interface:8 unmodified linesask_btn = gr.Button("Submit")answer = gr.Textbox(label="Answer")# Connect buttons to functionsupload_btn.click(upload_and_process, inputs=file_upload, outputs=output)ask_btn.click(ask_question, inputs=question_box, outputs=answer)# Launch Gradio interfaceinterface.launch()
app.py+71-7