Spaces:
Sleeping
Sleeping
| # streamlit_indian_compliance_app.py | |
| import streamlit as st | |
| import json | |
| import os | |
| import requests | |
| from dotenv import load_dotenv | |
| import pandas as pd | |
| from datetime import datetime | |
| import plotly.express as px | |
| import yfinance as yf | |
| import time | |
| from typing import Optional, Dict, Any, List | |
| # Load environment variables | |
| load_dotenv() | |
| # Configuration | |
| API_KEY = os.getenv("SWARMS_API_KEY") | |
| BASE_URL = "https://api.swarms.world" | |
| # Standard headers for all requests | |
| headers = { | |
| "x-api-key": API_KEY, | |
| "Content-Type": "application/json" | |
| } | |
| class IndianDataProvider: | |
| """Handles integration with Indian financial data APIs""" | |
| def __init__(self): | |
| pass | |
| def get_nse_stock_data(self, symbol: str) -> Dict[str, Any]: | |
| """Get NSE stock data using Yahoo Finance with direct metric extraction""" | |
| try: | |
| # Create ticker with NSE suffix | |
| ticker = yf.Ticker(f"{symbol}.NS") | |
| info = ticker.info | |
| financials = ticker.financials | |
| balance_sheet = ticker.balance_sheet | |
| cash_flow = ticker.cashflow | |
| # Extract key metrics directly from info | |
| current_price = info.get("currentPrice") | |
| total_revenue = info.get("totalRevenue") | |
| net_income = info.get("netIncomeToCommon") | |
| total_debt = info.get("totalDebt") | |
| return { | |
| 'success': True, | |
| 'info': info, | |
| 'financials': financials.to_dict() if not financials.empty else {}, | |
| 'balance_sheet': balance_sheet.to_dict() if not balance_sheet.empty else {}, | |
| 'cash_flow': cash_flow.to_dict() if not cash_flow.empty else {}, | |
| 'current_price': current_price, | |
| 'total_revenue': total_revenue, | |
| 'net_income': net_income, | |
| 'total_debt': total_debt, | |
| 'price_source': 'Yahoo Finance' | |
| } | |
| except Exception as e: | |
| return {"success": False, "error": str(e)} | |
| def format_stock_data_for_analysis(self, stock_data: Dict[str, Any]) -> str: | |
| """Format NSE stock data for compliance analysis""" | |
| if not stock_data.get('success'): | |
| return f"Error fetching stock data: {stock_data.get('error', 'Unknown error')}" | |
| try: | |
| info = stock_data['info'] | |
| financials = stock_data['financials'] | |
| balance_sheet = stock_data['balance_sheet'] | |
| # Use directly extracted metrics | |
| current_price = stock_data.get('current_price') | |
| total_revenue = stock_data.get('total_revenue') | |
| net_income = stock_data.get('net_income') | |
| total_debt = stock_data.get('total_debt') | |
| # Format currency values | |
| def format_currency(value): | |
| if value is None: | |
| return "N/A" | |
| return f"₹{value:,.2f}" | |
| def get_total_liabilities(balance_sheet: dict) -> float: | |
| for timestamp, financials in balance_sheet.items(): | |
| if 'Total Liabilities Net Minority Interest' in financials: | |
| return financials['Total Liabilities Net Minority Interest'] | |
| return None | |
| def get_total_assets(balance_sheet: dict) -> float: | |
| for timestamp, financials in balance_sheet.items(): | |
| if 'Total Assets' in financials: | |
| return financials['Total Assets'] | |
| return None | |
| total_assets = get_total_assets(balance_sheet) | |
| total_liabilities = get_total_liabilities(balance_sheet) | |
| shareholders_equity = total_assets - total_liabilities if total_assets and total_liabilities else None | |
| def get_ebitda(financials: dict) -> float: | |
| for timestamp, data in financials.items(): | |
| if 'EBITDA' in data: | |
| return data['EBITDA'] | |
| return None | |
| symbol_ebitda = get_ebitda(financials) | |
| def get_gross_profit(financials: dict) -> float: | |
| for timestamp, data in financials.items(): | |
| if 'Gross Profit' in data: | |
| return data['Gross Profit'] | |
| return None | |
| gross_profit = get_gross_profit(financials) | |
| def get_operating_income(financials: dict) -> float: | |
| for timestamp, data in financials.items(): | |
| if 'Operating Income' in data: | |
| return data['Operating Income'] | |
| return None | |
| operating_income = get_operating_income(financials) | |
| def get_operating_revenue(financials: dict) -> float: | |
| for timestamp, data in financials.items(): | |
| if 'Operating Revenue' in data: | |
| return data['Operating Revenue'] | |
| return None | |
| operating_revenue = get_operating_revenue(financials) | |
| def get_total_equity(balance_sheet: dict) -> float: | |
| for timestamp, data in balance_sheet.items(): | |
| if 'Total Equity Gross Minority Interest' in data: | |
| return data['Total Equity Gross Minority Interest'] | |
| return None | |
| total_equity = get_total_equity(balance_sheet) | |
| debt_to_equity = (total_debt / total_equity) if total_debt and total_equity else None | |
| formatted_data = f""" | |
| COMPANY INFORMATION: | |
| Company Name: {info.get('longName', 'N/A')} | |
| Symbol: {info.get('symbol', 'N/A')} | |
| Sector: {info.get('sector', 'N/A')} | |
| Industry: {info.get('industry', 'N/A')} | |
| Market Cap: {format_currency(info.get('marketCap'))} | |
| Employees: {info.get('fullTimeEmployees', 'N/A')} | |
| CURRENT PRICE: {format_currency(current_price)} (Source: Yahoo Finance) | |
| FINANCIAL HIGHLIGHTS: | |
| 52 Week High: {format_currency(info.get('fiftyTwoWeekHigh'))} | |
| 52 Week Low: {format_currency(info.get('fiftyTwoWeekLow'))} | |
| P/E Ratio: {info.get('trailingPE', 'N/A')} | |
| Book Value: {format_currency(info.get('bookValue'))} | |
| Dividend Yield: {info.get('dividendYield', 'N/A')}% | |
| FINANCIAL STATEMENTS: | |
| Revenue (Latest): {format_currency(total_revenue)} | |
| Net Income (Latest): {format_currency(net_income)} | |
| Total Assets (Latest): {format_currency(total_assets)} | |
| Total Debt (Latest): {format_currency(total_debt)} | |
| Total Equity (Latest): {format_currency(total_equity)} | |
| Debt to Equity Ratio: {(f"{debt_to_equity:.2f}" if debt_to_equity else "N/A")} | |
| Total Liabilities: {format_currency(total_liabilities)} | |
| Shareholders Equity: {format_currency(shareholders_equity)} | |
| EBITDA: {(format_currency(symbol_ebitda) if symbol_ebitda else "N/A")} | |
| Gross Profit: {format_currency(gross_profit)} | |
| Operating Income: {format_currency(operating_income)} | |
| Operating Revenue: {format_currency(operating_revenue)} | |
| BUSINESS SUMMARY: | |
| {info.get('longBusinessSummary', 'N/A')} | |
| GOVERNANCE: | |
| Board Members: {len(info.get('companyOfficers', []))} officers listed | |
| Audit Risk: {info.get('auditRisk', 'N/A')} | |
| Board Risk: {info.get('boardRisk', 'N/A')} | |
| Compensation Risk: {info.get('compensationRisk', 'N/A')} | |
| Shareholder Rights Risk: {info.get('shareHolderRightsRisk', 'N/A')} | |
| Overall Risk: {info.get('overallRisk', 'N/A')} | |
| """ | |
| return formatted_data.strip() | |
| except Exception as e: | |
| return f"Error formatting stock data: {str(e)}" | |
| def run_swarm(swarm_config): | |
| """Execute a swarm with the provided configuration.""" | |
| try: | |
| response = requests.post( | |
| f"{BASE_URL}/v1/swarm/completions", | |
| headers=headers, | |
| json=swarm_config | |
| ) | |
| return response.json() | |
| except Exception as e: | |
| return {"error": str(e)} | |
| def create_indian_compliance_swarm(financial_data, company_info): | |
| """Create a swarm for Indian financial compliance assistance.""" | |
| DOCUMENTATION_ANALYZER_PROMPT = """ | |
| You are a financial documentation specialist with expertise in Indian financial reporting standards and regulations. | |
| Your role is to analyze financial statements and disclosures for compliance with Indian requirements. | |
| Your tasks include: | |
| 1. Reviewing financial statements for completeness under Indian Accounting Standards (Ind AS) or AS | |
| 2. Analyzing annual reports and board reports for mandatory disclosures | |
| 3. Checking compliance with Companies Act 2013 disclosure requirements | |
| 4. Verifying CSR reporting and ESG disclosures as per Indian regulations | |
| 5. Ensuring proper disclosure of related party transactions under Indian law | |
| 6. Reviewing audit reports and internal financial control assessments | |
| 7. Checking compliance with SEBI disclosure norms (for listed companies) | |
| 8. Analyzing tax provisions and deferred tax disclosures under Indian tax laws | |
| Focus on Indian regulatory framework and provide findings specific to Indian compliance requirements. | |
| """ | |
| ACCOUNTING_STANDARDS_PROMPT = """ | |
| You are an expert in Indian Accounting Standards (Ind AS) and legacy Accounting Standards (AS) with deep knowledge of Indian GAAP requirements. | |
| Your responsibility is to ensure financial statements comply with applicable Indian accounting frameworks. | |
| Your tasks include: | |
| 1. Analyzing compliance with applicable Ind AS or AS standards | |
| 2. Reviewing revenue recognition under Ind AS 115 or AS 9 | |
| 3. Checking financial instrument accounting under Ind AS 109 or AS 30/31/32 | |
| 4. Evaluating lease accounting under Ind AS 116 or AS 19 | |
| 5. Reviewing impairment assessments under Ind AS 36 or AS 28 | |
| 6. Analyzing consolidation requirements under Ind AS 110/111 or AS 21/23/27 | |
| 7. Checking fair value measurements and disclosures under Ind AS 113 | |
| 8. Ensuring proper segment reporting under Ind AS 108 or AS 17 | |
| 9. Reviewing first-time adoption issues for Ind AS transition | |
| Reference specific Indian accounting standards and consider MCA notifications and clarifications. | |
| """ | |
| REGULATORY_COMPLIANCE_PROMPT = """ | |
| You are a senior regulatory compliance expert specializing in Indian financial regulations and corporate law. | |
| Your expertise covers Companies Act 2013, SEBI regulations, RBI guidelines, and other Indian regulatory frameworks. | |
| Your responsibilities include: | |
| 1. Ensuring compliance with Companies Act 2013 provisions and rules | |
| 2. Verifying SEBI LODR (Listing Obligations and Disclosure Requirements) compliance | |
| 3. Checking RBI guidelines compliance (for applicable sectors) | |
| 4. Reviewing corporate governance disclosures as per Indian regulations | |
| 5. Analyzing CSR compliance and reporting under Section 135 of Companies Act | |
| 6. Verifying board composition and audit committee requirements | |
| 7. Checking compliance with insider trading regulations (SEBI PIT) | |
| 8. Reviewing related party transaction approvals and disclosures | |
| 9. Ensuring proper filing requirements with MCA and SEBI | |
| 10. Analyzing compliance with sectoral regulations (banking, insurance, etc.) | |
| Focus on Indian regulatory environment and recent updates to regulations and compliance requirements. | |
| """ | |
| swarm_config = { | |
| "name": "Indian Financial Compliance Assistant", | |
| "description": "A specialized swarm for Indian financial regulatory compliance", | |
| "agents": [ | |
| { | |
| "agent_name": "Indian Documentation Analyzer", | |
| "description": "Reviews financial statements for Indian compliance requirements", | |
| "system_prompt": DOCUMENTATION_ANALYZER_PROMPT, | |
| "model_name": "gpt-4o", | |
| "role": "worker", | |
| "max_loops": 1, | |
| "max_tokens": 4096, | |
| "temperature": 0.5, | |
| "auto_generate_prompt": False, | |
| }, | |
| { | |
| "agent_name": "Indian Accounting Standards Expert", | |
| "description": "Evaluates compliance with Ind AS/AS requirements", | |
| "system_prompt": ACCOUNTING_STANDARDS_PROMPT, | |
| "model_name": "gpt-4o", | |
| "role": "worker", | |
| "max_loops": 1, | |
| "max_tokens": 4096, | |
| "temperature": 0.5, | |
| "auto_generate_prompt": False, | |
| }, | |
| { | |
| "agent_name": "Indian Regulatory Compliance Specialist", | |
| "description": "Assesses adherence to Indian regulatory frameworks", | |
| "system_prompt": REGULATORY_COMPLIANCE_PROMPT, | |
| "model_name": "gpt-4o", | |
| "role": "worker", | |
| "max_loops": 1, | |
| "max_tokens": 4096, | |
| "temperature": 0.5, | |
| "auto_generate_prompt": False, | |
| } | |
| ], | |
| "max_loops": 1, | |
| "swarm_type": "SequentialWorkflow", | |
| "task": f""" | |
| Analyze the following financial information for an Indian company ({company_info}) and provide a comprehensive compliance assessment according to Indian regulations: | |
| {financial_data} | |
| For your compliance evaluation, provide: | |
| 1. Assessment of compliance with Indian Accounting Standards (Ind AS/AS) | |
| 2. Analysis of Companies Act 2013 compliance requirements | |
| 3. Review of SEBI regulations compliance (if applicable) | |
| 4. Evaluation of corporate governance and disclosure requirements | |
| 5. Assessment of CSR and ESG reporting compliance | |
| 6. Identification of potential compliance risks specific to Indian regulations | |
| 7. Recommendations for improving compliance with Indian standards | |
| Focus specifically on Indian regulatory framework and recent regulatory updates. | |
| """ | |
| } | |
| return run_swarm(swarm_config) | |
| def create_comprehensive_csv_data(data_source, company_info, accounting_standards, regulatory_frameworks, result): | |
| """Create comprehensive CSV data with all analysis information""" | |
| # Extract company information | |
| company_parts = company_info.split(" in the ") | |
| company_type = company_parts[0] if len(company_parts) > 0 else "N/A" | |
| industry_sector = company_parts[1].split(", classified as")[0] if len(company_parts) > 1 else "N/A" | |
| company_size = company_parts[1].split("classified as ")[1].split(", for")[0] if len(company_parts) > 1 else "N/A" | |
| financial_year = company_parts[1].split("for ")[-1] if len(company_parts) > 1 else "N/A" | |
| # Create comprehensive data structure | |
| comprehensive_data = [] | |
| # 1. Basic Information | |
| comprehensive_data.append({ | |
| 'Category': 'Basic Information', | |
| 'Field': 'Analysis Timestamp', | |
| 'Value': datetime.now().strftime("%Y-%m-%d %H:%M:%S"), | |
| 'Details': 'Time when analysis was performed', | |
| 'Priority': '', | |
| 'Timeline': '', | |
| 'Regulation': '' | |
| }) | |
| comprehensive_data.append({ | |
| 'Category': 'Basic Information', | |
| 'Field': 'Data Source', | |
| 'Value': data_source, | |
| 'Details': 'Source of financial data used for analysis', | |
| 'Priority': '', | |
| 'Timeline': '', | |
| 'Regulation': '' | |
| }) | |
| comprehensive_data.append({ | |
| 'Category': 'Basic Information', | |
| 'Field': 'Company Type', | |
| 'Value': company_type, | |
| 'Details': 'Legal structure of the company', | |
| 'Priority': '', | |
| 'Timeline': '', | |
| 'Regulation': '' | |
| }) | |
| comprehensive_data.append({ | |
| 'Category': 'Basic Information', | |
| 'Field': 'Industry Sector', | |
| 'Value': industry_sector, | |
| 'Details': 'Primary business sector', | |
| 'Priority': '', | |
| 'Timeline': '', | |
| 'Regulation': '' | |
| }) | |
| comprehensive_data.append({ | |
| 'Category': 'Basic Information', | |
| 'Field': 'Company Size', | |
| 'Value': company_size, | |
| 'Details': 'Classification based on turnover and capital', | |
| 'Priority': '', | |
| 'Timeline': '', | |
| 'Regulation': '' | |
| }) | |
| comprehensive_data.append({ | |
| 'Category': 'Basic Information', | |
| 'Field': 'Financial Year', | |
| 'Value': financial_year, | |
| 'Details': 'Reporting period under analysis', | |
| 'Priority': '', | |
| 'Timeline': '', | |
| 'Regulation': '' | |
| }) | |
| comprehensive_data.append({ | |
| 'Category': 'Basic Information', | |
| 'Field': 'Accounting Standards', | |
| 'Value': accounting_standards, | |
| 'Details': 'Applicable accounting framework', | |
| 'Priority': '', | |
| 'Timeline': '', | |
| 'Regulation': '' | |
| }) | |
| comprehensive_data.append({ | |
| 'Category': 'Basic Information', | |
| 'Field': 'Regulatory Frameworks', | |
| 'Value': ', '.join(regulatory_frameworks), | |
| 'Details': 'Applicable regulatory requirements', | |
| 'Priority': '', | |
| 'Timeline': '', | |
| 'Regulation': '' | |
| }) | |
| # 2. AI Analysis Results (if available) | |
| if isinstance(result, dict) and 'response' in result: | |
| comprehensive_data.append({ | |
| 'Category': 'AI Analysis Results', | |
| 'Field': 'Full Analysis Response', | |
| 'Value': 'AI Generated Compliance Analysis', | |
| 'Details': result['response'][:1000] + '...' if len(result['response']) > 1000 else result['response'], | |
| 'Priority': '', | |
| 'Timeline': '', | |
| 'Regulation': '' | |
| }) | |
| return pd.DataFrame(comprehensive_data) | |
| def main(): | |
| st.set_page_config( | |
| page_title="Indian Financial Compliance System", | |
| page_icon="🇮🇳", | |
| layout="wide", | |
| initial_sidebar_state="expanded" | |
| ) | |
| # Initialize data provider | |
| if 'data_provider' not in st.session_state: | |
| st.session_state.data_provider = IndianDataProvider() | |
| # Header | |
| st.title("🇮🇳 Indian Financial Compliance & Regulatory System") | |
| st.markdown("AI-Powered Multi-Agent Financial Compliance Analysis for Indian Companies") | |
| # Sidebar Configuration | |
| with st.sidebar: | |
| st.header("Configuration") | |
| # API Key Check | |
| if not API_KEY: | |
| st.error("SWARMS_API_KEY not found in environment variables") | |
| st.info("Please set your API key in the .env file") | |
| return | |
| else: | |
| st.success("API Key configured") | |
| st.divider() | |
| # Data Source Selection | |
| st.subheader("📊 Data Source") | |
| data_source = st.selectbox( | |
| "Choose Data Source", | |
| [ | |
| "Manual Input", | |
| "NSE Listed Company (Live Data)" | |
| ], | |
| help="Select how you want to input financial data" | |
| ) | |
| financial_data = "" | |
| company_info_auto = "" | |
| # Handle different data sources | |
| if data_source == "NSE Listed Company (Live Data)": | |
| st.subheader("🔍 NSE Stock Data") | |
| # Popular Indian stocks for quick selection | |
| popular_stocks = [ | |
| 'ADANIENT', 'ADANIPORTS', 'APOLLOHOSP', 'ASIANPAINT', | |
| 'AXISBANK', 'BAJAJ-AUTO', 'BAJFINANCE', 'BAJAJFINSV', | |
| 'BEL', 'BHARTIARTL', 'CIPL', 'COALINDIA', 'DRREDDY', | |
| 'EICHERMOT', 'GRASIM', 'HCLTECH', 'HDFCBANK', 'HDFCLIFE', | |
| 'HEROMOTOCO', 'HINDALCO', 'HINDUNILVR', 'ICICIBANK', | |
| 'INDUSINDBK', 'INFY', 'ITC', 'JIOFIN', 'JSWSTEEL', | |
| 'KOTAKBANK', 'LT', 'M&M', 'MARUTI', 'NESTLEIND', | |
| 'NTPC', 'ONGC', 'POWERGRID', 'RELIANCE', 'SBILIFE', | |
| 'SHRIRAMFIN', 'SBIN', 'SUNPHARMA', 'TATACONSUM', 'TCS', | |
| 'TATAMOTORS', 'TATASTEEL', 'TECHM', 'TITAN', 'TRENT', | |
| 'ULTRACEMCO', 'WIPRO' | |
| ] | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| stock_symbol = st.selectbox( | |
| "Popular NSE Stocks", | |
| [""] + popular_stocks, | |
| help="Select from popular stocks" | |
| ) | |
| with col2: | |
| custom_symbol = st.text_input( | |
| "Enter Custom Symbol", | |
| placeholder="e.g., WIPRO", | |
| help="Enter NSE stock symbol" | |
| ) | |
| # Use custom symbol if provided, otherwise use selected | |
| symbol_to_fetch = custom_symbol.upper() if custom_symbol else stock_symbol | |
| if symbol_to_fetch and st.button("🚀 Fetch Live NSE Data", type="primary"): | |
| with st.spinner(f"Fetching live data for {symbol_to_fetch}..."): | |
| stock_data = st.session_state.data_provider.get_nse_stock_data(symbol_to_fetch) | |
| if stock_data.get('success'): | |
| st.success(f"✅ Successfully fetched data for {symbol_to_fetch}") | |
| financial_data = st.session_state.data_provider.format_stock_data_for_analysis(stock_data) | |
| company_info_auto = f"NSE Listed Company - {stock_data['info'].get('longName', symbol_to_fetch)} in {stock_data['info'].get('sector', 'Unknown')} sector" | |
| # Display quick preview with directly extracted metrics | |
| with st.expander("📋 Data Preview"): | |
| col_prev1, col_prev2 = st.columns(2) | |
| with col_prev1: | |
| st.metric("Market Cap", f"₹{stock_data['info'].get('marketCap', 0):,}") | |
| st.metric("Current Price", f"₹{stock_data.get('current_price', 0):,.2f}") | |
| with col_prev2: | |
| st.metric("Revenue", f"₹{stock_data.get('total_revenue', 0):,.2f}") | |
| st.metric("Net Income", f"₹{stock_data.get('net_income', 0):,.2f}") | |
| # Show data source info | |
| st.info(f"📊 Data Source: {stock_data.get('price_source', 'Unknown')}") | |
| else: | |
| st.error(f"❌ Failed to fetch data: {stock_data.get('error', 'Unknown error')}") | |
| st.divider() | |
| # Company Information (Auto-filled or Manual) | |
| st.subheader("🏢 Company Information") | |
| if company_info_auto: | |
| st.info(f"Auto-detected: {company_info_auto}") | |
| company_info = company_info_auto | |
| else: | |
| company_type = st.selectbox( | |
| "Company Type", | |
| [ | |
| "Public Limited Company", | |
| "Private Limited Company", | |
| "Listed Company", | |
| "Unlisted Public Company", | |
| "Small Company", | |
| "One Person Company (OPC)", | |
| "Section 8 Company (Non-Profit)", | |
| "Government Company", | |
| "Foreign Company" | |
| ] | |
| ) | |
| industry = st.selectbox( | |
| "Industry Sector", | |
| [ | |
| "Information Technology", | |
| "Banking & Financial Services", | |
| "Pharmaceuticals", | |
| "Automobile", | |
| "Textiles", | |
| "Steel & Metal", | |
| "Oil & Gas", | |
| "Telecommunications", | |
| "Real Estate", | |
| "Infrastructure", | |
| "Consumer Goods", | |
| "Healthcare", | |
| "Education", | |
| "Agriculture", | |
| "Other" | |
| ] | |
| ) | |
| company_size = st.selectbox( | |
| "Company Size", | |
| [ | |
| "Small Company (Turnover ≤ ₹20 Cr, Paid-up Capital ≤ ₹2 Cr)", | |
| "Medium Company", | |
| "Large Company", | |
| "Listed Company", | |
| "Multinational Company" | |
| ] | |
| ) | |
| financial_year = st.selectbox( | |
| "Financial Year", | |
| ["FY 2024-25", "FY 2023-24", "FY 2022-23", "FY 2021-22"] | |
| ) | |
| company_info = f"{company_type} in the {industry} sector, classified as {company_size}, for {financial_year}" | |
| # Applicable Standards | |
| st.subheader("📋 Standards & Regulations") | |
| accounting_standards = st.selectbox( | |
| "Accounting Standards", | |
| [ | |
| "Indian Accounting Standards (Ind AS)", | |
| "Accounting Standards (AS) - Old GAAP", | |
| "Both Ind AS and AS (Transition period)" | |
| ] | |
| ) | |
| regulatory_frameworks = st.multiselect( | |
| "Applicable Regulations", | |
| [ | |
| "Companies Act 2013", | |
| "SEBI LODR Regulations", | |
| "SEBI ICDR Regulations", | |
| "RBI Guidelines", | |
| "FEMA Regulations", | |
| "Income Tax Act 1961", | |
| "GST Regulations", | |
| "RERA (Real Estate)", | |
| "Insurance Regulatory Act", | |
| "Banking Regulation Act" | |
| ], | |
| default=["Companies Act 2013"] | |
| ) | |
| # Main Content Area | |
| col1, col2 = st.columns([2, 1]) | |
| with col1: | |
| st.subheader("📄 Financial Data Input") | |
| if data_source == "Manual Input" or not financial_data: | |
| # Manual input tabs | |
| tab1, tab2 = st.tabs(["✍️ Text Input", "📁 File Upload"]) | |
| with tab1: | |
| financial_data = st.text_area( | |
| "Enter Financial Statements and Related Information", | |
| value=financial_data, | |
| height=400, | |
| placeholder="""Enter your Indian financial data here, such as: | |
| • Balance Sheet as per Schedule III of Companies Act 2013 | |
| • Statement of Profit & Loss | |
| • Cash Flow Statement | |
| • Statement of Changes in Equity | |
| • Notes to Financial Statements | |
| • Board's Report | |
| • Management Discussion & Analysis (MD&A) | |
| • Corporate Governance Report | |
| • CSR Report | |
| • Auditor's Report | |
| • Internal Financial Control Report | |
| • Related Party Transactions | |
| • Segment Reporting (if applicable) | |
| • Subsidiary/Associate company details""" | |
| ) | |
| with tab2: | |
| uploaded_file = st.file_uploader( | |
| "Upload Financial Document", | |
| type=['txt'], | |
| help="Upload annual reports, financial statements, or compliance documents" | |
| ) | |
| if uploaded_file is not None: | |
| if uploaded_file.type == "text/plain": | |
| financial_data = str(uploaded_file.read(), "utf-8") | |
| st.success(f"✅ File uploaded: {uploaded_file.name}") | |
| else: | |
| # Display auto-fetched data with option to edit | |
| with st.expander("📊 Auto-Fetched Financial Data (Click to view/edit)", expanded=False): | |
| financial_data = st.text_area( | |
| "Financial Data (Auto-fetched - you can edit if needed)", | |
| value=financial_data, | |
| height=300 | |
| ) | |
| st.info(f"✅ Using data from: {data_source}") | |
| with col2: | |
| st.subheader("📊 Analysis Dashboard") | |
| # Quick metrics | |
| if 'compliance_result' in st.session_state: | |
| st.metric("Compliance Status", "Analyzed", "✓") | |
| st.metric("Data Source", data_source) | |
| st.metric("Analysis Count", len(st.session_state.get('analysis_history', []))) | |
| else: | |
| st.info("Analysis metrics will appear after running compliance check") | |
| # Data source info | |
| st.subheader("ℹ️ Current Configuration") | |
| st.write(f"**Data Source:** {data_source}") | |
| st.write(f"**Accounting Standards:** {accounting_standards}") | |
| st.write(f"**Regulations:** {', '.join(regulatory_frameworks[:2])}{'...' if len(regulatory_frameworks) > 2 else ''}") | |
| # Analysis History | |
| st.subheader("📚 Recent Analyses") | |
| if 'analysis_history' not in st.session_state: | |
| st.session_state.analysis_history = [] | |
| if st.session_state.analysis_history: | |
| for i, analysis in enumerate(st.session_state.analysis_history[-3:]): | |
| with st.expander(f"Analysis {len(st.session_state.analysis_history) - i}"): | |
| st.text(f"Date: {analysis['timestamp']}") | |
| st.text(f"Source: {analysis['data_source']}") | |
| st.text(f"Company: {analysis['company_info'][:50]}...") | |
| st.text(f"Status: {analysis['status']}") | |
| else: | |
| st.info("No previous analyses") | |
| # Analysis Controls | |
| st.divider() | |
| col_run, col_options = st.columns([1, 2]) | |
| with col_run: | |
| run_analysis = st.button( | |
| "🚀 Run Indian Compliance Analysis", | |
| type="primary", | |
| use_container_width=True, | |
| disabled=not bool(financial_data.strip()) | |
| ) | |
| with col_options: | |
| with st.expander("⚙️ Advanced Options"): | |
| col_adv1, col_adv2 = st.columns(2) | |
| with col_adv1: | |
| focus_areas = st.multiselect( | |
| "Focus Areas", | |
| [ | |
| "Revenue Recognition (Ind AS 115)", | |
| "Related Party Transactions", | |
| "Corporate Social Responsibility", | |
| "Board Governance", | |
| "Audit Committee Compliance", | |
| "Segment Reporting", | |
| "Consolidation Requirements" | |
| ] | |
| ) | |
| with col_adv2: | |
| analysis_depth = st.selectbox( | |
| "Analysis Depth", | |
| ["Standard", "Detailed", "Comprehensive"] | |
| ) | |
| # Run Analysis | |
| if run_analysis: | |
| if not financial_data.strip(): | |
| st.error("⚠️ Please provide financial data to analyze") | |
| return | |
| with st.spinner("🔄 Running multi-agent Indian compliance analysis..."): | |
| # Progress tracking | |
| progress_bar = st.progress(0) | |
| status_text = st.empty() | |
| status_text.text("🤖 Initializing Indian compliance agents...") | |
| progress_bar.progress(20) | |
| time.sleep(1) | |
| status_text.text("📋 Analyzing documentation compliance...") | |
| progress_bar.progress(40) | |
| time.sleep(1) | |
| status_text.text("📊 Evaluating Indian accounting standards...") | |
| progress_bar.progress(60) | |
| time.sleep(1) | |
| status_text.text("⚖️ Checking regulatory compliance...") | |
| progress_bar.progress(80) | |
| time.sleep(1) | |
| # Run the analysis | |
| result = create_indian_compliance_swarm(financial_data, company_info) | |
| progress_bar.progress(100) | |
| status_text.text("✅ Analysis complete!") | |
| time.sleep(1) | |
| # Clear progress indicators | |
| progress_bar.empty() | |
| status_text.empty() | |
| # Store results | |
| st.session_state.compliance_result = result | |
| # Add to history | |
| st.session_state.analysis_history.append({ | |
| 'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S"), | |
| 'data_source': data_source, | |
| 'company_info': company_info, | |
| 'status': 'Completed' | |
| }) | |
| # Display Results | |
| if 'compliance_result' in st.session_state: | |
| st.divider() | |
| st.header("📊 Indian Compliance Analysis Results") | |
| result = st.session_state.compliance_result | |
| if "error" in result: | |
| st.error(f"❌ Analysis failed: {result['error']}") | |
| return | |
| # Results tabs | |
| tab1, tab2, tab3 = st.tabs([ | |
| "📋 Executive Summary", | |
| "🔍 Detailed Analysis", | |
| "⚖️ Risk Assessment" | |
| ]) | |
| with tab1: | |
| st.subheader("Executive Summary") | |
| # Display actual API results | |
| st.subheader("🤖 AI Analysis Output") | |
| if isinstance(result, dict) and 'response' in result: | |
| with st.container(): | |
| st.markdown("---") | |
| st.write(result['response']) | |
| else: | |
| with st.expander("Raw API Response"): | |
| st.json(result) | |
| with tab2: | |
| st.subheader("🔍 Detailed Agent Analysis") | |
| agents = [ | |
| ("📋", "Indian Documentation Analyzer", "Documentation compliance assessment"), | |
| ("📊", "Indian Accounting Standards Expert", "Accounting standards evaluation"), | |
| ("⚖️", "Indian Regulatory Compliance Specialist", "Regulatory compliance review") | |
| ] | |
| for icon, agent, description in agents: | |
| with st.expander(f"{icon} {agent} Results"): | |
| st.write(f"**Agent:** {agent}") | |
| st.write(f"**Focus:** {description}") | |
| if "Documentation" in agent: | |
| st.write("**Key Areas Reviewed:**") | |
| st.write("• Annual report completeness assessment") | |
| st.write("• Board report adequacy review") | |
| st.write("• Mandatory disclosure verification") | |
| st.write("• CSR reporting compliance") | |
| elif "Accounting" in agent: | |
| st.write("**Standards Evaluated:**") | |
| st.write("• Ind AS/AS compliance evaluation") | |
| st.write("• Revenue recognition analysis") | |
| st.write("• Financial instrument accounting review") | |
| st.write("• Consolidation requirements check") | |
| else: | |
| st.write("**Regulations Assessed:**") | |
| st.write("• Companies Act 2013 compliance") | |
| st.write("• SEBI regulation adherence") | |
| st.write("• Corporate governance assessment") | |
| st.write("• Filing requirements validation") | |
| with tab3: | |
| st.subheader("⚖️ Indian Regulatory Risk Assessment") | |
| # Risk categories specific to Indian context | |
| risk_data = { | |
| 'Risk Area': [ | |
| 'Companies Act Compliance', | |
| 'Ind AS Implementation', | |
| 'SEBI Regulations', | |
| 'CSR Compliance', | |
| 'Corporate Governance', | |
| 'Tax Compliance' | |
| ], | |
| 'Risk Level': ['Medium', 'Low', 'Medium', 'High', 'Low', 'Medium'], | |
| 'Impact Score': [7, 4, 6, 9, 3, 5], | |
| 'Likelihood Score': [5, 3, 6, 8, 2, 4] | |
| } | |
| df_risk = pd.DataFrame(risk_data) | |
| # Risk matrix visualization | |
| fig = px.scatter( | |
| df_risk, | |
| x='Impact Score', | |
| y='Likelihood Score', | |
| color='Risk Level', | |
| size='Impact Score', | |
| hover_data=['Risk Area'], | |
| title="Indian Regulatory Risk Matrix", | |
| color_discrete_map={'High': '#FF6B6B', 'Medium': '#FFD93D', 'Low': '#6BCF7F'}, | |
| labels={'Impact Score': 'Impact →', 'Likelihood Score': 'Likelihood →'} | |
| ) | |
| fig.update_layout( | |
| xaxis_range=[0, 10], | |
| yaxis_range=[0, 10], | |
| height=500 | |
| ) | |
| st.plotly_chart(fig, use_container_width=True) | |
| st.subheader("📊 Risk Summary Table") | |
| st.dataframe(df_risk, use_container_width=True) | |
| # Export functionality | |
| st.divider() | |
| st.subheader("📤 Export Results") | |
| col_exp1, col_exp2 = st.columns(2) | |
| with col_exp1: | |
| # Create comprehensive CSV data | |
| comprehensive_df = create_comprehensive_csv_data( | |
| data_source, company_info, accounting_standards, regulatory_frameworks, result | |
| ) | |
| csv_data = comprehensive_df.to_csv(index=False) | |
| st.download_button( | |
| "📋 Download Analysis CSV", | |
| data=csv_data, | |
| file_name=f"compliance_analysis_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv", | |
| mime="text/csv" | |
| ) | |
| # Show preview of CSV data | |
| with st.expander("📊 CSV Data Preview"): | |
| st.dataframe(comprehensive_df, use_container_width=True, height=300) | |
| with col_exp2: | |
| json_result = json.dumps(result, indent=2) | |
| st.download_button( | |
| "💾 Download JSON", | |
| data=json_result, | |
| file_name=f"indian_compliance_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json", | |
| mime="application/json" | |
| ) | |
| if __name__ == "__main__": | |
| main() |