Download app.py from AVIBYOURCOMPANION/AVIB_YOURCOMPANION: direct link, hf CLI and curl.
- Browser
- Download file 23.6 kB
-
https://huggingface.co/AVIBYOURCOMPANION/AVIB_YOURCOMPANION/resolve/main/app.py
- Command line
-
hf download hf://AVIBYOURCOMPANION/AVIB_YOURCOMPANION/app.py
-
curl -L -o app.py https://huggingface.co/AVIBYOURCOMPANION/AVIB_YOURCOMPANION/resolve/main/app.py
23.6 kB
| # π AVIACHI - Professional Document Analysis Assistant | |
| import gradio as gr | |
| import requests | |
| import json | |
| import pandas as pd | |
| import numpy as np | |
| from PIL import Image | |
| import PyPDF2 | |
| import os | |
| import random | |
| from docx import Document | |
| import traceback | |
| # Your Groq API key - Set this in Hugging Face Secrets | |
| GROQ_API_KEY = os.getenv("GROQ_API_KEY") | |
| # Simple professional responses | |
| RESPONSES = [ | |
| "Analysis complete! Hope this helps with your work, Sir! π", | |
| "Document processed successfully. Let me know if you need anything else, Sir! β ", | |
| "Here's your comprehensive analysis. Feel free to ask follow-up questions, Sir! π", | |
| "Task completed! I'm ready for your next question, Sir! πΌ", | |
| "Analysis ready! Ask me anything about your document, Sir! π" | |
| ] | |
| # CLEAN PROFESSIONAL CSS - Minimal & Clean | |
| PROFESSIONAL_CSS = """ | |
| /* Simple professional fonts */ | |
| @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap'); | |
| /* Clean container styling */ | |
| .gradio-container { | |
| font-family: 'Inter', system-ui, sans-serif !important; | |
| background: #f8f9fa !important; | |
| color: #2c3e50 !important; | |
| } | |
| /* Professional headers */ | |
| h1, h2, h3 { | |
| font-family: 'Inter', system-ui, sans-serif !important; | |
| color: #2c3e50 !important; | |
| font-weight: 600 !important; | |
| } | |
| h1 { font-size: 2rem !important; } | |
| h2 { font-size: 1.5rem !important; } | |
| h3 { font-size: 1.2rem !important; } | |
| /* Clean body text */ | |
| p, div, span, label { | |
| font-family: 'Inter', system-ui, sans-serif !important; | |
| font-size: 14px !important; | |
| line-height: 1.5 !important; | |
| color: #495057 !important; | |
| } | |
| /* Professional input styling */ | |
| input[type="text"], textarea { | |
| background: #ffffff !important; | |
| border: 2px solid #e9ecef !important; | |
| border-radius: 8px !important; | |
| color: #495057 !important; | |
| font-family: 'Inter', system-ui, sans-serif !important; | |
| font-size: 14px !important; | |
| padding: 12px !important; | |
| transition: border-color 0.2s ease !important; | |
| } | |
| input:focus, textarea:focus { | |
| border-color: #007bff !important; | |
| outline: none !important; | |
| box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1) !important; | |
| } | |
| input::placeholder, textarea::placeholder { | |
| color: #6c757d !important; | |
| font-style: normal !important; | |
| } | |
| /* Clean button styling */ | |
| button { | |
| background: #007bff !important; | |
| border: none !important; | |
| border-radius: 6px !important; | |
| color: #ffffff !important; | |
| font-family: 'Inter', system-ui, sans-serif !important; | |
| font-size: 14px !important; | |
| font-weight: 500 !important; | |
| padding: 10px 20px !important; | |
| cursor: pointer !important; | |
| transition: background-color 0.2s ease !important; | |
| } | |
| button:hover { | |
| background: #0056b3 !important; | |
| } | |
| button[variant="secondary"] { | |
| background: #6c757d !important; | |
| color: #ffffff !important; | |
| } | |
| button[variant="secondary"]:hover { | |
| background: #545b62 !important; | |
| } | |
| /* Professional chatbot styling */ | |
| .gr-chatbot { | |
| background: #ffffff !important; | |
| border: 1px solid #dee2e6 !important; | |
| border-radius: 8px !important; | |
| } | |
| /* Clean file upload */ | |
| .gr-file { | |
| background: #f8f9fa !important; | |
| border: 2px dashed #dee2e6 !important; | |
| border-radius: 8px !important; | |
| padding: 20px !important; | |
| } | |
| .gr-file:hover { | |
| border-color: #007bff !important; | |
| background: #f0f8ff !important; | |
| } | |
| /* Professional labels */ | |
| label { | |
| color: #495057 !important; | |
| font-family: 'Inter', system-ui, sans-serif !important; | |
| font-size: 14px !important; | |
| font-weight: 500 !important; | |
| margin-bottom: 6px !important; | |
| } | |
| /* Clean examples */ | |
| .gr-examples button { | |
| background: #f8f9fa !important; | |
| border: 1px solid #dee2e6 !important; | |
| color: #495057 !important; | |
| padding: 8px 16px !important; | |
| border-radius: 6px !important; | |
| font-size: 13px !important; | |
| margin: 4px !important; | |
| } | |
| .gr-examples button:hover { | |
| background: #e9ecef !important; | |
| border-color: #007bff !important; | |
| } | |
| /* Mobile responsive */ | |
| @media (max-width: 768px) { | |
| h1 { font-size: 1.5rem !important; } | |
| h2 { font-size: 1.2rem !important; } | |
| p, div, span { font-size: 13px !important; } | |
| input, textarea { font-size: 14px !important; padding: 10px !important; } | |
| button { padding: 8px 16px !important; font-size: 13px !important; } | |
| } | |
| """ | |
| def detect_file_type(file_path): | |
| """Auto-detect file type from extension""" | |
| try: | |
| ext = os.path.splitext(file_path)[1].lower() | |
| if ext == '.pdf': | |
| return 'pdf' | |
| elif ext in ['.csv', '.xlsx', '.xls']: | |
| return 'data' | |
| elif ext in ['.png', '.jpg', '.jpeg', '.gif', '.bmp']: | |
| return 'image' | |
| elif ext in ['.txt', '.md']: | |
| return 'text' | |
| elif ext in ['.doc', '.docx']: | |
| return 'legal_doc' | |
| else: | |
| return 'unknown' | |
| except Exception as e: | |
| print(f"File type detection error: {e}") | |
| return 'unknown' | |
| def extract_docx_content(file_path): | |
| """Extract content from Word documents""" | |
| try: | |
| doc = Document(file_path) | |
| full_text = [] | |
| for paragraph in doc.paragraphs: | |
| if paragraph.text.strip(): | |
| full_text.append(paragraph.text) | |
| tables_content = [] | |
| try: | |
| for table in doc.tables: | |
| table_data = [] | |
| for row in table.rows: | |
| row_data = [cell.text.strip() for cell in row.cells] | |
| table_data.append(row_data) | |
| tables_content.append(table_data) | |
| except: | |
| tables_content = [] | |
| return { | |
| 'paragraphs': full_text, | |
| 'tables': tables_content, | |
| 'full_text': '\n'.join(full_text), | |
| 'word_count': len('\n'.join(full_text).split()) if full_text else 0 | |
| } | |
| except Exception as e: | |
| return { | |
| 'error': str(e), | |
| 'full_text': f'Error reading document: {str(e)}', | |
| 'paragraphs': [], | |
| 'tables': [], | |
| 'word_count': 0 | |
| } | |
| def create_simple_dashboard(file_info, file_type): | |
| """Create clean professional dashboard""" | |
| try: | |
| if file_type == 'legal_doc': | |
| content = file_info.get('content', {}) | |
| dashboard_html = f""" | |
| <div style=" | |
| background: #ffffff; | |
| border: 1px solid #dee2e6; | |
| border-radius: 8px; | |
| padding: 20px; | |
| margin: 16px 0; | |
| font-family: 'Inter', system-ui, sans-serif; | |
| "> | |
| <h3 style="color: #495057; margin: 0 0 16px 0; font-size: 18px;">π Document Analysis Summary</h3> | |
| <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 16px;"> | |
| <div style="background: #f8f9fa; padding: 16px; border-radius: 6px;"> | |
| <h4 style="color: #495057; margin: 0 0 12px 0; font-size: 14px;">Document Details</h4> | |
| <p style="margin: 4px 0; font-size: 13px;"><strong>Word Count:</strong> {content.get('word_count', 0):,}</p> | |
| <p style="margin: 4px 0; font-size: 13px;"><strong>Paragraphs:</strong> {len(content.get('paragraphs', []))}</p> | |
| <p style="margin: 4px 0; font-size: 13px;"><strong>Tables:</strong> {len(content.get('tables', []))}</p> | |
| </div> | |
| <div style="background: #f8f9fa; padding: 16px; border-radius: 6px;"> | |
| <h4 style="color: #495057; margin: 0 0 12px 0; font-size: 14px;">Analysis Status</h4> | |
| <p style="margin: 4px 0; font-size: 13px;"><strong>Processing:</strong> Complete β </p> | |
| <p style="margin: 4px 0; font-size: 13px;"><strong>Quality:</strong> Good</p> | |
| <p style="margin: 4px 0; font-size: 13px;"><strong>Ready:</strong> For review</p> | |
| </div> | |
| </div> | |
| </div> | |
| """ | |
| elif file_type == 'data': | |
| content = file_info.get('content', {}) | |
| dashboard_html = f""" | |
| <div style=" | |
| background: #ffffff; | |
| border: 1px solid #dee2e6; | |
| border-radius: 8px; | |
| padding: 20px; | |
| margin: 16px 0; | |
| font-family: 'Inter', system-ui, sans-serif; | |
| "> | |
| <h3 style="color: #495057; margin: 0 0 16px 0; font-size: 18px;">π Data File Summary</h3> | |
| <div style="background: #f8f9fa; padding: 16px; border-radius: 6px;"> | |
| <p style="margin: 6px 0; font-size: 14px;"><strong>Rows:</strong> {content.get('shape', [0, 0])[0]:,}</p> | |
| <p style="margin: 6px 0; font-size: 14px;"><strong>Columns:</strong> {content.get('shape', [0, 0])[1]}</p> | |
| <p style="margin: 6px 0; font-size: 14px;"><strong>Missing Values:</strong> {content.get('missing', 0):,}</p> | |
| <p style="margin: 6px 0; font-size: 14px;"><strong>Status:</strong> Ready for analysis β </p> | |
| </div> | |
| </div> | |
| """ | |
| else: | |
| dashboard_html = f""" | |
| <div style=" | |
| background: #ffffff; | |
| border: 1px solid #dee2e6; | |
| border-radius: 8px; | |
| padding: 20px; | |
| margin: 16px 0; | |
| font-family: 'Inter', system-ui, sans-serif; | |
| text-align: center; | |
| "> | |
| <h3 style="color: #495057; margin: 0 0 12px 0; font-size: 18px;">π File Processed</h3> | |
| <p style="font-size: 14px; color: #6c757d;">File Type: {file_info.get('type', 'Unknown')}</p> | |
| <p style="font-size: 14px; color: #28a745;">β Successfully uploaded and ready for analysis</p> | |
| </div> | |
| """ | |
| return dashboard_html | |
| except Exception as e: | |
| return f'<div style="color: #dc3545; padding: 16px; text-align: center;">Error creating summary: {str(e)}</div>' | |
| def process_any_file(file): | |
| """Process uploaded files""" | |
| if not file: | |
| return None, None | |
| try: | |
| file_type = detect_file_type(file.name) | |
| if file_type == 'legal_doc': | |
| docx_content = extract_docx_content(file.name) | |
| return { | |
| 'type': 'Word Document', | |
| 'content': docx_content, | |
| 'analysis_type': 'legal_document' | |
| }, file_type | |
| elif file_type == 'data': | |
| try: | |
| if file.name.endswith('.csv'): | |
| df = pd.read_csv(file.name) | |
| else: | |
| df = pd.read_excel(file.name) | |
| summary = { | |
| 'shape': df.shape, | |
| 'columns': df.columns.tolist()[:10], | |
| 'missing': int(df.isnull().sum().sum()), | |
| 'numeric_cols': len(df.select_dtypes(include=[np.number]).columns) | |
| } | |
| return { | |
| 'type': 'Data File', | |
| 'content': summary, | |
| 'analysis_type': 'data' | |
| }, file_type | |
| except Exception as data_error: | |
| return { | |
| 'type': 'Data File Error', | |
| 'content': f'Error processing data file: {str(data_error)}', | |
| 'analysis_type': 'error' | |
| }, 'error' | |
| elif file_type == 'pdf': | |
| try: | |
| pdf_reader = PyPDF2.PdfReader(file.name) | |
| text = "" | |
| for page in pdf_reader.pages: | |
| text += page.extract_text() + "\n" | |
| return { | |
| 'type': 'PDF Document', | |
| 'content': text[:5000], | |
| 'pages': len(pdf_reader.pages), | |
| 'analysis_type': 'pdf' | |
| }, file_type | |
| except Exception as pdf_error: | |
| return { | |
| 'type': 'PDF Error', | |
| 'content': f'Error processing PDF: {str(pdf_error)}', | |
| 'analysis_type': 'error' | |
| }, 'error' | |
| else: | |
| return { | |
| 'type': 'File', | |
| 'content': f'File uploaded: {file.name}', | |
| 'analysis_type': 'unknown' | |
| }, file_type | |
| except Exception as e: | |
| return { | |
| 'type': 'Processing Error', | |
| 'content': f'Error: {str(e)}', | |
| 'analysis_type': 'error' | |
| }, 'error' | |
| def get_analysis(file_info, user_message=""): | |
| """Get AI analysis with simplified prompts""" | |
| try: | |
| if not GROQ_API_KEY: | |
| return "Please configure GROQ_API_KEY in the Hugging Face Space secrets." | |
| headers = { | |
| 'Authorization': f'Bearer {GROQ_API_KEY}', | |
| 'Content-Type': 'application/json' | |
| } | |
| if file_info.get('analysis_type') == 'legal_document': | |
| content = file_info.get('content', {}) | |
| full_text = content.get('full_text', '') | |
| prompt = f"""Analyze this document professionally: | |
| Document Content: | |
| {full_text[:3000]} | |
| Please provide: | |
| 1. Document Summary | |
| 2. Key Points Analysis | |
| 3. Recommendations | |
| 4. Next Steps | |
| User Question: {user_message if user_message else 'Comprehensive analysis'} | |
| Keep response professional and address the user as "Sir".""" | |
| elif file_info.get('analysis_type') == 'data': | |
| content = file_info.get('content', {}) | |
| prompt = f"""Analyze this data file: | |
| Data Overview: | |
| - Rows: {content.get('shape', [0, 0])[0]:,} | |
| - Columns: {content.get('shape', [0, 0])[1]} | |
| - Missing: {content.get('missing', 0)} | |
| Provide data insights and recommendations. | |
| User question: {user_message or 'Data analysis'} | |
| Keep response professional and address the user as "Sir".""" | |
| else: | |
| prompt = f"""Analyze this file: | |
| File Type: {file_info.get('type', 'Unknown')} | |
| Content: {file_info.get('content', 'No content available')} | |
| User question: {user_message or 'File analysis'} | |
| Provide professional insights and address the user as "Sir".""" | |
| data = { | |
| 'model': 'llama-3.3-70b-versatile', | |
| 'messages': [ | |
| {'role': 'system', 'content': 'You are AVIACHI, a professional document analyst. Provide clear, actionable analysis. Always call the user "Sir" and maintain a professional tone.'}, | |
| {'role': 'user', 'content': prompt} | |
| ], | |
| 'max_tokens': 1500, | |
| 'temperature': 0.2 | |
| } | |
| response = requests.post( | |
| 'https://api.groq.com/openai/v1/chat/completions', | |
| headers=headers, | |
| json=data, | |
| timeout=45 | |
| ) | |
| if response.status_code == 200: | |
| result = response.json() | |
| return result['choices'][0]['message']['content'] | |
| else: | |
| return f"Analysis complete! File processed successfully, Sir." | |
| except Exception as e: | |
| return f"File processed successfully! Ready for analysis, Sir." | |
| def aviachi_chat(message, history, uploaded_file): | |
| """Main chat function with clean interface""" | |
| try: | |
| # Handle file upload | |
| if uploaded_file: | |
| file_info, file_type = process_any_file(uploaded_file) | |
| if file_info: | |
| dashboard_html = create_simple_dashboard(file_info, file_type) | |
| analysis = get_analysis(file_info, message) | |
| # Simple detection message | |
| if file_info.get('analysis_type') == 'legal_document': | |
| content = file_info.get('content', {}) | |
| detection_msg = f"""## Document Analysis Complete | |
| **File Type:** Word Document | |
| **Word Count:** {content.get('word_count', 0):,} words | |
| **Status:** Ready for review | |
| """ | |
| elif file_info.get('analysis_type') == 'data': | |
| content = file_info.get('content', {}) | |
| detection_msg = f"""## Data File Processed | |
| **File Type:** Data File | |
| **Records:** {content.get('shape', [0, 0])[0]:,} rows | |
| **Status:** Ready for analysis | |
| """ | |
| else: | |
| detection_msg = f"""## File Uploaded | |
| **File Type:** {file_info.get('type', 'Unknown')} | |
| **Status:** Successfully processed | |
| """ | |
| response_line = random.choice(RESPONSES) | |
| full_response = f"{detection_msg}\n\n{dashboard_html}\n\n{analysis}\n\n---\n\n{response_line}" | |
| history.append([f"π File: {uploaded_file.name}", full_response]) | |
| return history, "", None | |
| else: | |
| error_response = """## Processing Error | |
| Unable to process the file. Please try: | |
| - Different file format | |
| - Smaller file size | |
| - Supported formats: PDF, Word, Excel, CSV""" | |
| history.append([f"π File Error: {uploaded_file.name}", error_response]) | |
| return history, "", None | |
| # Handle regular chat | |
| if message and message.strip(): | |
| # Handle greetings | |
| if any(word in message.lower() for word in ['hello', 'hi', 'hey']): | |
| greeting = """# Welcome to AVIACHI | |
| Hello Sir! I'm your document analysis assistant. | |
| ## What I Can Help With: | |
| **Document Analysis:** | |
| - Legal document review | |
| - Contract analysis | |
| - Policy review | |
| **Data Analysis:** | |
| - Spreadsheet insights | |
| - Data quality review | |
| - Statistical summaries | |
| **File Processing:** | |
| - PDF text extraction | |
| - Word document analysis | |
| - Excel data processing | |
| ## How to Get Started: | |
| 1. Upload your document using the file uploader below | |
| 2. Ask me specific questions about your files | |
| 3. Get professional analysis and insights | |
| Ready to help with your documents, Sir!""" | |
| history.append([message, greeting]) | |
| return history, "", None | |
| # Regular AI chat | |
| try: | |
| if not GROQ_API_KEY: | |
| error_response = "Please configure GROQ_API_KEY in the Hugging Face Space secrets to enable AI responses." | |
| history.append([message, error_response]) | |
| return history, "", None | |
| headers = { | |
| 'Authorization': f'Bearer {GROQ_API_KEY}', | |
| 'Content-Type': 'application/json' | |
| } | |
| data = { | |
| 'model': 'llama-3.3-70b-versatile', | |
| 'messages': [ | |
| {'role': 'system', 'content': 'You are AVIACHI, a professional assistant. Be helpful, call users "Sir", and provide clear advice. Keep responses concise and professional.'}, | |
| {'role': 'user', 'content': message} | |
| ], | |
| 'max_tokens': 1200, | |
| 'temperature': 0.3 | |
| } | |
| response = requests.post( | |
| 'https://api.groq.com/openai/v1/chat/completions', | |
| headers=headers, | |
| json=data, | |
| timeout=30 | |
| ) | |
| if response.status_code == 200: | |
| result = response.json() | |
| ai_response = result['choices'][0]['message']['content'] | |
| response_line = random.choice(RESPONSES) | |
| full_response = f"{ai_response}\n\n---\n\n{response_line}" | |
| history.append([message, full_response]) | |
| return history, "", None | |
| else: | |
| error_response = "I'm having trouble connecting right now. Please try again, Sir!" | |
| history.append([message, error_response]) | |
| return history, "", None | |
| except Exception as e: | |
| error_response = "I'm experiencing a technical issue. Please try again, Sir!" | |
| history.append([message, error_response]) | |
| return history, "", None | |
| return history, "", None | |
| except Exception as e: | |
| error_response = "System error occurred. Please try again, Sir!" | |
| history.append(["System Error", error_response]) | |
| return history, "", None | |
| def handle_submit(message, history, file): | |
| try: | |
| return aviachi_chat(message, history, file) | |
| except Exception as e: | |
| error_msg = f"Processing error: {str(e)}" | |
| history.append([message or "File Upload", error_msg]) | |
| return history, "", None | |
| def clear_chat(): | |
| return [], "", None | |
| # Create Gradio interface | |
| def create_interface(): | |
| with gr.Blocks( | |
| css=PROFESSIONAL_CSS, | |
| title="AVIACHI - Document Analysis Assistant", | |
| theme=gr.themes.Soft() | |
| ) as interface: | |
| # Clean header | |
| gr.HTML(""" | |
| <div style="text-align: center; padding: 20px 0; background: #ffffff; border: 1px solid #dee2e6; border-radius: 8px; margin-bottom: 20px;"> | |
| <h1 style="font-family: 'Inter', system-ui, sans-serif; font-size: 1.8rem; color: #495057; margin: 0; font-weight: 600;"> | |
| AVIACHI Document Assistant | |
| </h1> | |
| <p style="font-family: 'Inter', system-ui, sans-serif; font-size: 14px; color: #6c757d; margin: 8px 0 0 0;"> | |
| Professional document analysis and insights | |
| </p> | |
| </div> | |
| """) | |
| # Chat interface | |
| chatbot = gr.Chatbot( | |
| value=[], | |
| height=400, | |
| show_label=False, | |
| avatar_images=None, | |
| bubble_full_width=False, | |
| show_copy_button=True, | |
| render_markdown=True | |
| ) | |
| # Input section | |
| with gr.Row(): | |
| with gr.Column(scale=4): | |
| msg = gr.Textbox( | |
| label="Ask a question", | |
| placeholder="Type your message here...", | |
| show_label=True, | |
| lines=2, | |
| max_lines=4 | |
| ) | |
| with gr.Column(scale=1): | |
| submit = gr.Button("Send", variant="primary", size="lg") | |
| # File upload and controls | |
| with gr.Row(): | |
| with gr.Column(scale=3): | |
| upload = gr.File( | |
| label="Upload Document", | |
| file_count="single", | |
| file_types=[".pdf", ".docx", ".doc", ".csv", ".xlsx", ".xls"] | |
| ) | |
| with gr.Column(scale=1): | |
| clear = gr.Button("Clear Chat", variant="secondary", size="lg") | |
| # Simple examples | |
| gr.Examples( | |
| examples=[ | |
| ["Hello! What can you help me with?"], | |
| ["Analyze this document for key points"], | |
| ["What insights can you provide from this data?"], | |
| ["Summarize the main findings"], | |
| ["What are the next steps I should take?"] | |
| ], | |
| inputs=msg | |
| ) | |
| # Connect events | |
| submit.click( | |
| handle_submit, | |
| inputs=[msg, chatbot, upload], | |
| outputs=[chatbot, msg, upload] | |
| ) | |
| msg.submit( | |
| handle_submit, | |
| inputs=[msg, chatbot, upload], | |
| outputs=[chatbot, msg, upload] | |
| ) | |
| upload.change( | |
| handle_submit, | |
| inputs=[msg, chatbot, upload], | |
| outputs=[chatbot, msg, upload] | |
| ) | |
| clear.click( | |
| clear_chat, | |
| outputs=[chatbot, msg, upload] | |
| ) | |
| return interface | |
| # Launch the interface | |
| if __name__ == "__main__": | |
| demo = create_interface() | |
| demo.launch() |