Spaces:
Sleeping
Sleeping
Update utils.py
Browse files1234368 unmodified lines373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763<<<<<<< HEADimport streamlit as stfrom groq import Groqimport io368 unmodified linesdef format_timestamp(timestamp):"""Format timestamp for display"""return timestamp.strftime("%Y-%m-%d %H:%M:%S")=======# utils.pyimport streamlit as stfrom groq import Groqimport ioimport base64import reimport osfrom dotenv import load_dotenvfrom llama_index.core import VectorStoreIndex, Settings, Documentfrom llama_index.readers.file import PDFReaderfrom llama_index.llms.groq import Groq as LlamaGroqfrom llama_index.embeddings.langchain import LangchainEmbeddingfrom langchain_community.embeddings import HuggingFaceEmbeddingsfrom datetime import datetimefrom PIL import Image# Load environment variables and configureload_dotenv()groq_api_key = os.getenv("GROQ_API_KEY")client = Groq(api_key=groq_api_key)# Configure LlamaIndexSettings.llm = LlamaGroq(api_key=groq_api_key, model="llama-3.1-70b-versatile")lc_embed_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")Settings.embed_model = LangchainEmbedding(lc_embed_model)def initialize_session_state():"""Initialize all session state variables"""if 'chat_engines' not in st.session_state:st.session_state.chat_engines = {}if 'analyses' not in st.session_state:st.session_state.analyses = {}if 'documents' not in st.session_state:st.session_state.documents = {}if 'current_doc' not in st.session_state:st.session_state.current_doc = Noneif 'messages' not in st.session_state:st.session_state.messages = []if 'document_history' not in st.session_state:st.session_state.document_history = {}def encode_image_to_base64(image):"""Convert PIL Image to base64 string"""buffered = io.BytesIO()image.save(buffered, format="JPEG")return base64.b64encode(buffered.getvalue()).decode()def process_image(image):"""Process image using Llama vision model"""img_base64 = encode_image_to_base64(image)img_url = f"data:image/jpeg;base64,{img_base64}"completion = client.chat.completions.create(model="llama-3.2-11b-vision-preview",messages=[{"role": "user","content": [{"type": "text","text": """Please analyze this government document and provide:1. Document type and purpose2. Key requirements and deadlines3. Complex terms explained simply4. Required actions or next steps5. Important contact information or submission details"""},{"type": "image_url","image_url": {"url": img_url}}]}],temperature=0.1,max_tokens=1024,top_p=1,stream=False)return completion.choices[0].message.contentdef generate_pdf_analysis(documents):"""Generate analysis from PDF documents using Groq"""try:# Combine all document contentfull_text = "\n".join([doc.text for doc in documents])# Generate analysis using Groqcompletion = client.chat.completions.create(model="llama-3.1-70b-versatile",messages=[{"role": "user","content": ("Please analyze this government document and provide:\n""1. Document Type and Purpose:\n"" - What kind of document is this?\n"" - What is its main purpose?\n\n""2. Key Requirements:\n"" - What are the main requirements or conditions?\n"" - What documents or information are needed?\n\n""3. Important Deadlines:\n"" - What are the key dates and deadlines?\n"" - Are there any time-sensitive requirements?\n\n""4. Complex Terms Explained:\n"" - Explain any technical or legal terms in simple language\n"" - Clarify any complex procedures\n\n""5. Required Actions:\n"" - What steps need to be taken?\n"" - What is the process to follow?\n\n""6. Contact Information:\n"" - Who to contact for queries?\n"" - Where to submit the documents?\n\n""Document content:\n" + full_text)}],temperature=0.1,max_tokens=2048,top_p=1)# Format the analysis with proper stylinganalysis = completion.choices[0].message.contentcompletionsum = client.chat.completions.create(model="llama-3.1-8b-instant",messages=[{"role": "user","content": ("Summarize the following content: " + analysis)}],temperature=0.1,max_tokens=2048,top_p=1)analysis = completionsum.choices[0].message.content# Add formatting for better readabilityformatted_analysis = ("<div class='analysis-container'>""<div class='analysis-section'>" +analysis.replace('\n\n', '</div><div class="analysis-section">') +"</div>""</div>")return formatted_analysisexcept Exception as e:error_msg = "Error generating PDF analysis: " + str(e)raise Exception(error_msg)def clean_llm_output(output):"""Clean LLM output by removing HTML tags and formatting symbols"""# Remove HTML tagscleaned_text = re.sub(r'<[^>]+>', '', output)# Remove double asteriskscleaned_text = cleaned_text.replace('**', '')cleaned_text = cleaned_text.replace('*', '')# Remove extra whitespacecleaned_text = re.sub(r'\s+', ' ', cleaned_text)return cleaned_text.strip()def format_analysis_results(text):"""Format analysis results into structured HTML"""# First clean the textcleaned_text = clean_llm_output(text)# Split into sectionssections = []current_section = ""current_title = ""for line in cleaned_text.split('\n'):line = line.strip()if ':' in line and not line.startswith('*'):# If we have a previous section, save itif current_title:sections.append((current_title, current_section.strip()))# Start new sectionparts = line.split(':', 1)current_title = parts[0].strip()current_section = parts[1].strip() if len(parts) > 1 else ""else:current_section += " " + line# Add the last sectionif current_title:sections.append((current_title, current_section.strip()))# Generate HTMLhtml = "<div class='analysis-results'>"for title, content in sections:html += f"""<div class='analysis-section card' style='margin-bottom: 1rem;'><h4 style='color: #60A5FA; margin-bottom: 0.5rem;'>{title}</h4><p style='margin: 0;'>{content}</p></div>"""html += "</div>"return htmldef process_captured_image(picture):"""Process image captured from camera with mobile-friendly UI"""try:# Show processing statusstatus_placeholder = st.empty()status_placeholder.markdown("<div class='status-badge status-warning'>""๐ธ Processing captured image...""</div>",unsafe_allow_html=True)# Process the imageimage = Image.open(picture)# Display the captured image with proper mobile sizingst.image(image,caption="Captured Document",use_column_width=True # Makes image responsive)# Process image with AIwith st.spinner("Analyzing document..."):analysis = process_image(image)# Generate filename with timestamptimestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")filename = f"captured_image_{timestamp}"# Save resultsst.session_state.analyses[filename] = {'type': 'image/jpeg','analysis': analysis,'timestamp': datetime.datetime.now()}# Create chat enginest.session_state.chat_engines[filename] = create_chat_engine(analysis)# Save to historysave_to_history(filename,'Captured Image',analysis,datetime.datetime.now())# Update status to successstatus_placeholder.markdown("<div class='status-badge status-success'>""โ Image analyzed successfully!""</div>",unsafe_allow_html=True)# Display analysis resultsst.markdown("<div class='card'>""<h4>Analysis Results</h4>"f"<div style='margin: 1rem 0;'>{analysis}</div>""</div>",unsafe_allow_html=True)# Mobile-friendly action buttonsst.markdown("<div class='touch-spacing'>", unsafe_allow_html=True)col1, col2 = st.columns(2)with col1:if st.button("๐ฌ Start Chat", use_container_width=True):st.session_state.current_doc = filenamest.switch_page("pages/Document_Chat.py")with col2:if st.button("๐ธ New Capture", use_container_width=True):st.rerun()st.markdown("</div>", unsafe_allow_html=True)except Exception as e:st.error("โ Error processing image\n"f"Details: {str(e)}")def process_pdf(pdf_file):"""Process PDF document using LlamaIndex"""temp_dir = "temp_docs"os.makedirs(temp_dir, exist_ok=True)temp_path = os.path.join(temp_dir, "temp.pdf")with open(temp_path, "wb") as f:f.write(pdf_file.getvalue())try:reader = PDFReader()documents = reader.load_data(temp_path)return documentsfinally:if os.path.exists(temp_path):os.remove(temp_path)if os.path.exists(temp_dir) and not os.listdir(temp_dir):os.rmdir(temp_dir)def create_chat_engine(content):"""Create chat engine from document content"""if isinstance(content, str):documents = [Document(text=content)]else:documents = contentindex = VectorStoreIndex.from_documents(documents)return index.as_chat_engine(chat_mode="condense_question", verbose=True)def generate_document(doc_type, fields):"""Generate government documents based on type and fields"""prompt = f"""Generate a formal {doc_type} with the following details:{fields}Please format this as a proper official document following standard government formatting."""completion = client.chat.completions.create(model="llama-3.1-70b-versatile",messages=[{"role": "user","content": prompt}],temperature=0.7,max_tokens=2048,top_p=1)return completion.choices[0].message.contentdef save_to_history(doc_name, doc_type, content, timestamp=None):"""Save document to history with metadata"""if timestamp is None:timestamp = datetime.now()st.session_state.document_history[doc_name] = {'type': doc_type,'content': content,'timestamp': timestamp,'status': 'Processed'}def get_document_history():"""Retrieve document history sorted by timestamp"""history = st.session_state.document_historyreturn dict(sorted(history.items(),key=lambda x: x[1]['timestamp'],reverse=True))def delete_from_history(doc_name):"""Delete document from history"""if doc_name in st.session_state.document_history:del st.session_state.document_history[doc_name]if doc_name in st.session_state.chat_engines:del st.session_state.chat_engines[doc_name]if doc_name in st.session_state.analyses:del st.session_state.analyses[doc_name]if st.session_state.current_doc == doc_name:st.session_state.current_doc = Nonedef format_timestamp(timestamp):"""Format timestamp for display"""return timestamp.strftime("%Y-%m-%d %H:%M:%S")>>>>>>> 1bc20a0d3edc7f88f03e506f84b01a7303d403b2123368 unmodified lines372373374375import streamlit as stfrom groq import Groqimport io368 unmodified linesdef format_timestamp(timestamp):"""Format timestamp for display"""return timestamp.strftime("%Y-%m-%d %H:%M:%S")
utils.py+1-389