Spaces:
Runtime error
Runtime error
Download app.py from siddani93/AIFAQSystem: direct link, hf CLI and curl.
- Browser
- Download file 8.5 kB
-
https://huggingface.co/spaces/siddani93/AIFAQSystem/resolve/main/app.py
- Command line
-
hf download hf://spaces/siddani93/AIFAQSystem/app.py
-
curl -L -o app.py https://huggingface.co/spaces/siddani93/AIFAQSystem/resolve/main/app.py
8.5 kB
| import streamlit as st | |
| import google.generativeai as genai | |
| import time | |
| import PyPDF2 | |
| from datetime import datetime | |
| from io import BytesIO | |
| from knowledge_base import get_industrial_answer | |
| from pdf2image import convert_from_bytes | |
| # Configuration | |
| try: | |
| genai.configure( | |
| api_key=st.secrets["GOOGLE_API_KEY"], | |
| client_options={"api_endpoint": "generativelanguage.googleapis.com/v1beta"} | |
| ) | |
| model = genai.GenerativeModel( | |
| 'gemini-1.5-flash-latest', | |
| generation_config={ | |
| "temperature": 0.3, | |
| "max_output_tokens": 500, | |
| "response_mime_type": "text/plain" | |
| }, | |
| safety_settings={ | |
| "HARASSMENT": "BLOCK_NONE", | |
| "HATE": "BLOCK_NONE", | |
| "SEXUAL": "BLOCK_NONE", | |
| "DANGEROUS": "BLOCK_NONE" | |
| } | |
| ) | |
| except Exception as config_error: | |
| st.error(f"Configuration Error: {str(config_error)}") | |
| st.stop() | |
| # Custom CSS for dark/light mode | |
| def inject_custom_css(): | |
| st.markdown(f""" | |
| <style> | |
| .stApp {{ | |
| background-color: {st.session_state.bg_color}; | |
| color: {st.session_state.text_color}; | |
| }} | |
| .sidebar .sidebar-content {{ | |
| background-color: {st.session_state.sidebar_bg} !important; | |
| }} | |
| .chat-message {{ | |
| padding: 1rem; | |
| border-radius: 0.5rem; | |
| margin-bottom: 1rem; | |
| background: {st.session_state.msg_bg}; | |
| }} | |
| </style> | |
| """, unsafe_allow_html=True) | |
| # System prompt template | |
| SYSTEM_PROMPT = """**Invoice Analysis Expert** | |
| Analyze the provided document and extract: | |
| 1. Invoice Number | |
| 2. Total Amount | |
| 3. Due Date | |
| 4. Vendor/Customer Name | |
| 5. Itemized Charges | |
| Follow these rules: | |
| - Present data in markdown table | |
| - Highlight important dates/amounts in bold | |
| - Cross-verify with company policies | |
| - Current Date: {date} | |
| - Language: {language} | |
| Document Content: | |
| {file_content} | |
| User Question: {question} | |
| """ | |
| def process_uploaded_files(files): | |
| """Process uploaded files for analysis""" | |
| processed = [] | |
| if not files: | |
| return processed | |
| for file in files: | |
| try: | |
| file_bytes = file['bytes'] | |
| mime_type = file['type'] | |
| if mime_type == "application/pdf": | |
| try: | |
| # Try native PDF handling | |
| processed.append( | |
| genai.upload_file( | |
| mime_type="application/pdf", | |
| file=BytesIO(file_bytes) | |
| ) | |
| except Exception as pdf_error: | |
| # Fallback to text extraction | |
| pdf_text = "" | |
| pdf_reader = PyPDF2.PdfReader(BytesIO(file_bytes)) | |
| for page in pdf_reader.pages[:3]: # First 3 pages only | |
| page_text = page.extract_text() | |
| if page_text: | |
| pdf_text += page_text + "\n" | |
| if pdf_text.strip(): | |
| processed.append(pdf_text) | |
| else: | |
| # Convert PDF to images | |
| images = convert_from_bytes(file_bytes, first_page=0, last_page=2) | |
| for img in images: | |
| img_byte_arr = BytesIO() | |
| img.save(img_byte_arr, format='JPEG') | |
| processed.append( | |
| genai.upload_file( | |
| mime_type="image/jpeg", | |
| file=img_byte_arr | |
| ) | |
| ) | |
| elif mime_type.startswith("image/"): | |
| processed.append( | |
| genai.upload_file( | |
| mime_type=mime_type, | |
| file=BytesIO(file_bytes) | |
| ) | |
| ) | |
| except Exception as e: | |
| st.error(f"Error processing {file['name']}: {str(e)}") | |
| continue | |
| return processed | |
| def generate_response(prompt: str, language: str, files: list) -> str: | |
| """Generate response with document analysis""" | |
| start_time = time.time() | |
| try: | |
| # Process files first | |
| file_contents = process_uploaded_files(files) | |
| if not file_contents: | |
| return "β οΈ Could not process any uploaded documents" | |
| # Build prompt | |
| formatted_prompt = SYSTEM_PROMPT.format( | |
| date=datetime.now().strftime("%Y-%m-%d"), | |
| language=language, | |
| file_content="\n\n".join([ | |
| f"Document {i+1} Content:\n" + | |
| (content if isinstance(content, str) else "[Image Content]") | |
| for i, content in enumerate(file_contents) | |
| ]), | |
| question=prompt | |
| ) | |
| # Generate response | |
| response = model.generate_content( | |
| [formatted_prompt] + file_contents, | |
| request_options={"timeout": 30} | |
| ) | |
| return response.text if response.text else "No relevant information found" | |
| except Exception as e: | |
| return f"Analysis Error: {str(e)}" | |
| finally: | |
| if time.time() - start_time > 25: | |
| st.error("Analysis timeout. Try smaller documents or specific questions.") | |
| # Session State Management | |
| if "messages" not in st.session_state: | |
| st.session_state.messages = [] | |
| if "files" not in st.session_state: | |
| st.session_state.files = [] | |
| if "dark_mode" not in st.session_state: | |
| st.session_state.dark_mode = False | |
| if "language" not in st.session_state: | |
| st.session_state.language = "English" | |
| # Theme Configuration | |
| theme = { | |
| "dark": { | |
| "bg": "#1a1a1a", | |
| "text": "#ffffff", | |
| "sidebar": "#2d2d2d", | |
| "msg": "#333333" | |
| }, | |
| "light": { | |
| "bg": "#ffffff", | |
| "text": "#000000", | |
| "sidebar": "#f0f0f0", | |
| "msg": "#f8f9fa" | |
| } | |
| } | |
| # Apply theme | |
| mode = "dark" if st.session_state.dark_mode else "light" | |
| st.session_state.bg_color = theme[mode]["bg"] | |
| st.session_state.text_color = theme[mode]["text"] | |
| st.session_state.sidebar_bg = theme[mode]["sidebar"] | |
| st.session_state.msg_bg = theme[mode]["msg"] | |
| # Sidebar Controls | |
| with st.sidebar: | |
| st.title("βοΈ Settings") | |
| # Theme Toggle | |
| st.session_state.dark_mode = st.toggle( | |
| "π Dark Mode", | |
| value=st.session_state.dark_mode | |
| ) | |
| # Language Selector | |
| st.session_state.language = st.selectbox( | |
| "π Select Language", | |
| ["English", "Spanish", "French", "German", "Chinese"], | |
| index=0 | |
| ) | |
| # Chat History | |
| st.subheader("π Chat History") | |
| history_expander = st.expander("View History") | |
| with history_expander: | |
| for idx, msg in enumerate(st.session_state.messages): | |
| if msg["role"] == "user": | |
| st.markdown(f"**You ({idx+1}):** {msg['content']}") | |
| else: | |
| st.markdown(f"**TARS ({idx+1}):** {msg['content']}") | |
| # File Uploader | |
| st.subheader("π Upload Documents") | |
| uploaded_files = st.file_uploader( | |
| "Select PDF/Image files", | |
| type=["pdf", "png", "jpg", "jpeg"], | |
| accept_multiple_files=True, | |
| label_visibility="collapsed" | |
| ) | |
| if uploaded_files: | |
| st.session_state.files = [{ | |
| "name": file.name, | |
| "type": file.type, | |
| "bytes": file.read() | |
| } for file in uploaded_files] | |
| # Main Interface | |
| st.title("π€ Industrial Document Analyst") | |
| st.caption("Your AI-powered document analysis assistant") | |
| # Chat Interface | |
| for message in st.session_state.messages: | |
| with st.chat_message(message["role"]): | |
| st.markdown(message["content"], unsafe_allow_html=True) | |
| # User Input | |
| if prompt := st.chat_input("Ask about your documents..."): | |
| # Add user message | |
| st.session_state.messages.append({ | |
| "role": "user", | |
| "content": f"**{prompt}**" | |
| }) | |
| # Generate response | |
| with st.spinner("π Analyzing documents..."): | |
| reply = generate_response( | |
| prompt, | |
| st.session_state.language, | |
| st.session_state.files | |
| ) | |
| # Add assistant response | |
| st.session_state.messages.append({ | |
| "role": "assistant", | |
| "content": reply | |
| }) | |
| # Rerun to update display | |
| st.rerun() | |
| # Apply CSS last | |
| inject_custom_css() |