- 🎯 Overview
⇧ - 🌟 Features
⇧ - 🏗️ Architecture
⇧ - 🛠️ Environment setup
⇧ - 🧩 Project Structure
⇧ - 👥 Contributors
⇧
🎯 Overview ⇧
An advanced AI-powered system that analyzes Egyptian legal contracts using AWS services. It provides comprehensive legal analysis, compliance checking, and risk assessment for Arabic legal documents.
🌟Features ⇧
- 🔍 Advanced Arabic OCR: High-accuracy text extraction from contract images
- 🤖 Multi-Agent Analysis: Specialized AI agents for different legal aspects
- ⚖️ Egyptian Law Compliance: Automated checking against Egyptian legal requirements
- 🌐 Bilingual Support: Analysis and reports in both Arabic and English
- ⚡ Real-time Processing: Fast analysis with cloud-native architecture
🏗️ Architecture ⇧
This system processes user-submitted documents through a sophisticated pipeline that combines OCR, AI analysis, and knowledge management.
- User Interaction: Users submit requests through Amazon CloudFront (CDN for global content delivery)
- Static Content: The S3 Static Website Bucket hosts the web interface
- API Gateway: Amazon API Gateway handles incoming API requests and routes them appropriately
- Processing Trigger: An Orchestration Lambda Function coordinates the document processing workflow
The OCR Lambda Function performs optical character recognition on uploaded documents, extracting text from images or scanned PDFs. This processed text is then passed to the core analysis engine.
The heart of the system is the AgentCore Runtime, which contains two specialized AI agents:
- Contract Explanation Agent: Analyzes and explains contract terms and clauses
- Contract Assessment Agent: Evaluates contracts for risks, obligations, and key provisions
These agents leverage Amazon Bedrock (AWS's managed foundation model service) to perform sophisticated natural language understanding and generation tasks.
The system incorporates:
- Amazon Bedrock Knowledge Base: Provides domain-specific knowledge and context
- S3 Knowledge Base Data Source: Stores reference documents and training data
- Guardrails: Ensures AI responses comply with defined safety and accuracy parameters
The AgentCore Memory component maintains context and conversation history, enabling more coherent multi-turn interactions.
- Amazon CloudFront: Content delivery network
- S3: Object storage for static website and knowledge base
- API Gateway: RESTful API management
- Lambda Functions: Serverless compute for OCR and orchestration
- Amazon Bedrock: Managed AI/ML foundation models
- Guardrails: AI safety and compliance controls
- Explanation Mode: Detailed contract breakdown and explanation
- Assessment Mode: Risk assessment and legal recommendations
- Interactive Chat: Follow-up questions with session-based conversation memory
🚀 Quick Start ⇧
- AWS Account with appropriate permissions
- Python 3.9+
- AWS CLI configured
- Access to AWS Bedrock AgentCore
git clone [repository-url]
cd egyptian-legal-contract-analysispip install -r requirements.txt# Configure AWS CLI
aws configure
# Configure AgentCore
agentcore configurechmod +x deploy.sh
./deploy.shcd deployment
# Deploy main Lambda function
zip -r lambda-deployment.zip lambda_function.py
aws lambda create-function \
--function-name egyptian-legal-contract-api \
--runtime python3.9 \
--role arn:aws:iam::YOUR-ACCOUNT:role/egyptian-legal-lambda-role \
--handler lambda_function.lambda_handler \
--zip-file fileb://lambda-deployment.zip
# Deploy OCR processor
zip -r ocr-deployment.zip ocr_processor.py
aws lambda create-function \
--function-name ocr-processor \
--runtime python3.9 \
--role arn:aws:iam::YOUR-ACCOUNT:role/egyptian-legal-lambda-role \
--handler ocr_processor.lambda_handler \
### 6. Deploy Website
```bash
# Upload website to S3
aws s3 cp production_website_aws.html s3://egyptian-legal-analysis-ui/production_website_aws.html
# Configure S3 for static website hosting
aws s3 website s3://egyptian-legal-analysis-ui --index-document production_website_aws.htmlCreate API Gateway with the following endpoints:
GET /health→ Main LambdaPOST /api/analyze→ Main LambdaPOST /api/ask→ Main LambdaPOST /api/ocr→ Main Lambda
Enable CORS for all endpoints.
Configuration ⇧
The Lambda execution role needs permissions for:
- Bedrock AgentCore access
- Lambda function invocation
- CloudWatch logging
- S3 bucket access (for knowledge base only)
Set these in your Lambda functions:
AWS_REGION=us-west-2KNOWLEDGE_BASE_ID=QJWEBKNQ1N
Update these in deployment/lambda_function.py:
- Explanation Agent:
arn:aws:bedrock-agentcore:us-west-2:YOUR-ACCOUNT:runtime/memoryenhancedexplanation-XXXXX - Assessment Agent:
arn:aws:bedrock-agentcore:us-west-2:YOUR-ACCOUNT:runtime/memoryenhancedassessment-XXXXX
API Documentation ⇧
GET /health
Response: {"status": "healthy", "service": "Egyptian Legal Contract Analysis API"}POST /api/analyze
Content-Type: application/json
{
"analysis_type": "explanation|assessment",
"contract_text": "نص العقد...",
"user_id": "optional_user_id"
}POST /api/ask
Content-Type: application/json
{
"question": "ما هي حقوق الموظف؟",
"contract_text": "نص العقد...",
"user_id": "user_id",
"session_id": "session_id"
}POST /api/ocr
Content-Type: application/json
{
"image_data": "data:image/jpeg;base64,/9j/4AAQ...",
"auto_analyze": true,
"analysis_type": "explanation"
}Egyptian Law Knowledge Base ⇧
Our system includes a list of comprehensive knowledge (for testing):
- قانون العمل رقم 12 لسنة 2003 (Labor Law No. 12/2003)
- القانون المدني المصري (Egyptian Civil Code)
- قوانين العقارات والإيجارات (Real Estate & Rental Laws)
- القوانين التجارية (Commercial Laws)
- السوابق القضائية (Legal Precedents)
Live Demo ⇧
- Website: http://egyptian-legal-analysis-ui.s3-website-us-west-2.amazonaws.com/
- API Base URL: https://820uxym01d.execute-api.us-west-2.amazonaws.com/prod
Usage Examples ⇧
- Visit the website
- Select analysis type (Explanation or Assessment)
- Upload contract image or paste text
- Click "تحليل العقد" to get AI-powered analysis
- After analysis, ask follow-up questions
- Get detailed responses based on contract content
- Continue conversation with context preservation
- Upload contract image
- Click "استخراج النص ومعالجته"
- Get extracted Arabic text
- Optionally run automatic analysis
Monitoring and Debugging ⇧
Monitor the following log groups:
/aws/lambda/egyptian-legal-contract-api/aws/lambda/ocr-processor
- AgentCore Not Available: Check agent deployment and ARNs
- OCR Failures: Verify image format and size
- CORS Errors: Ensure proper API Gateway CORS configuration
- Memory Issues: Increase Lambda memory allocation
Environment setup ⇧
- First and foremost, please see the suggested IDE setup in the dropdown below to make sure that your editor is ready for development.
Important
Suggested IDE setup
VS Code
Install the following extensions:
- Fork the AI-Legal-Checker repo, clone your fork, and configure the remotes:
Note
Consider using SSH
Alternatively to using HTTPS as in the instructions below, consider SSH to interact with GitHub from the terminal. SSH allows you to connect without a user-pass authentication flow.
To run git commands with SSH, remember then to substitute the HTTPS URL, https://github.com/..., with the SSH one, [email protected]:....
- e.g. Cloning now becomes
git clone [email protected]:<your-username>/AI-Legal-Checker.git
GitHub also has their documentation on how to Generate a new SSH key 🔑
# Clone your fork of the repo into the current directory.
git clone https://github.com/<your-username>/AI-Legal-Checker
# Navigate to the newly cloned directory.
cd AI-Legal-Checker
# Assign the original repo to a remote called "upstream".
git remote add upstream https://github.com/activist-org/AI-Legal-Checker- Now, if you run
git remote -vyou should see two remote repositories named:origin(forked repository)upstream(AI-Legal-Checker repository)
-
Create a virtual environment, activate it and install dependencies:
# Unix or MacOS: python3 -m venv venv source venv/bin/activate # Windows: python -m venv venv venv\Scripts\activate.bat # After activating venv: pip install --upgrade pip pip install -r requirements-dev.txt # To install the AI-Legal-Checker for local development: pip install -e .
You're now ready to work on AI-Legal-Checker!
Option 1. Contract Upload and Analysis.
-
Visit the website
-
Select analysis type (Explanation or Assessment)
-
Upload contract image or paste text
-
Click "تحليل العقد" to get AI-powered analysis
Option 2. Interactive Q&A#
-
After analysis, ask follow-up questions
-
Get detailed responses based on contract content
-
Continue conversation with context preservation
-
Upload contract image "s3Configuration": {
-
Click "استخراج النص ومعالجته"
-
Get extracted Arabic text
-
Optionally run automatic analysis
-
Fork the repository
-
Create a feature branch
-
Make your changes
-
Add tests for new functionality
-
Submit a pull request
For issues and questions:
- Check the docs/ folder for detailed documentation
- Review CloudWatch logs for debugging
- Ensure all AWS services are properly configured
- Verify agent deployment status
Contract Text → AgentCore Agent → RAG Knowledge Base → Bedrock LLM → Enhanced Analysis
Image Upload → OCR Processor → Claude Vision → Arabic Text → Optional Analysis
User Question → AgentCore (with memory) → RAG Enhancement → Contextual Response
egyptian-legal-contract-analysis/
├── README.md # This file
├── requirements.txt # Python dependencies
├── production_website_aws.html # Main website
├── lambda-trust-policy.json # IAM trust policy
├── .bedrock_agentcore.yaml # AgentCore configuration
├── architecture_diagram.png # System architecture diagram
├── agents/ # Agent configurations
│ ├── contract_explanation_agent.py
│ ├── contract_assessment_agent.py
│ └── contract_assessment_agent_rag.py
├── deployment/ # Lambda deployment files
│ ├── lambda_function.py # Main API Lambda
│ └── ocr_processor.py # OCR processing Lambda
├── setup_aws_infrastructure.py # Infrastructure setup
├── knowledge_base_manager.py # Knowledge base management
├── create_simple_rag_agent.py # RAG agent creation
└── deploy_agents.py # Agent deployment
This project is licensed under the MIT License - see the LICENSE file for details.
Contributors ⇧
Thanks to all our amazing contributors! ❤️

