Skip to content

Latest commit

 

History

11 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Contract Analysis Tool (Azure OpenAI & Google Gemini)

Disclaimer: This tool performs an analysis of legal documents. It does not provide legal advice, and its use does not establish an attorney-client relationship or attorney-client privilege. If you require attorney-client privilege or legal counsel, please consult with a qualified attorney. The results generated by this should not be relied upon as a substitute for professional legal advice.

This tool automates the analysis of various legal contracts (PDF, Word, Excel, Images) using Large Language Models (LLMs). It supports Azure OpenAI (GPT-4) and Google Gemini (2.0 Flash), allowing for flexible, high-capacity document review across different contract types.

Key Features

  • Hybrid Provider Support: Switch between Azure OpenAI and Google Gemini.
  • Dynamic Context Window: Automatically splits large contracts into overlapping chunks based on the selected model's capacity ("Vik's Rule" — 25% of the model's context window), analyzes each chunk, and synthesizes results.
  • Multi-Format Support: Extracts text from PDFs (OCR enabled), Word docs (.docx, .doc), Rich Text Format (.rtf), Excel files (.xlsx), and common image formats.
  • Long Path Support: Handles file paths exceeding Windows' 260-character limit via extended-length path prefixes.
  • Excel Reporting: Generates a structured Excel report (ai_results.xlsx) with analysis results for each contract.
  • GUI & CLI: Modern, user-friendly graphical interface and robust command-line interface.

1. Prerequisites

  • Python 3.10+ (Recommended)
  • Tesseract OCR (for scanned PDFs/Images)

2. Dependencies

Install the required Python packages:

pip install -r requirements.txt

3. Configuration

Environment Variables (Authentication)

Create a .env file or set these variables in your system:

For Azure OpenAI:

  • AZURE_OPENAI_API_KEY: (Optional) If using API Key auth. If not set, the tool attempts Azure AD authentication (CLI, VS Code, Browser).

For Google Gemini:

  • API Key: Set GOOGLE_API_KEY environment variable.
  • OAuth (Recommended): Download client_secret.json from Google Cloud Console.
    • Create a Project > APIs & Services > Credentials.
    • Create "OAuth 2.0 Client ID" (Desktop App).
    • Download the JSON file and save it (e.g., as client_secret.json).

Prompts

  • The tool uses YAML files (e.g., LOI_Contract_prompts.yaml, Customer_prompts.yaml) to define the analysis questions.
  • Each YAML file may include a top-level global_instructions string that is automatically prepended to every prompt in that file. Use this for cross-cutting directives such as citation requirements.
  • Format:
    global_instructions: >
      Include clause/section citations for each material finding where available.
    
    prompts:
      - column_header: "Parties Involved"
        prompt: "Identify the buyer and seller in this contract."
      - column_header: "Effective Date"
        prompt: "What is the effective date of the agreement?"

4. Usage

Graphical Interface (GUI)

Simply run the script without arguments to launch the GUI:

python Contract_Analysis.py
  • Select Input: Local folder or file.
  • Provider: Choose between Google (Gemini 2.0 Flash - Default) and Azure (GPT-4o).
  • Auth Method:
    • Google: OAuth (Recommended), API Key, or ADC.
    • Azure: RBAC or API Key.
  • Contract Type: Select the type of contract to analyze (LOI, Customer, Employment, Supplier, Manufacturing, Retail). This will load the corresponding prompt file by default.

Command Line Interface (CLI)

Run headlessly for automation:

# Analyze a folder for LOI contracts using Google Gemini (Default)
python Contract_Analysis.py --input "C:\Contracts" --output "ai_results.xlsx" --contract-type loi

# Analyze customer contracts using Azure OpenAI
python Contract_Analysis.py --input "C:\Contracts" --provider azure --contract-type customer

# Specify a specific model and contract type
python Contract_Analysis.py --input "C:\Contracts" --provider google --model gemini-2.0-flash-001 --contract-type employment

5. Context Window Logic ("Vik's Rule")

The tool dynamically calculates the safe amount of text to send based on the model's context window:

target_tokens = context_window × 25%    (VIK_RULE_UTILIZATION)
max_chars     = target_tokens  × 3.5    (CHARS_PER_TOKEN)
Model Context Window Vik's Rule Limit
GPT-4o 128,000 tokens ~32,000 tokens (~112,000 chars)
Gemini 2.0 Flash 1,000,000 tokens ~250,000 tokens (~875,000 chars)
Gemini 1.5 Pro 2,000,000 tokens ~500,000 tokens (~1,750,000 chars)

Chunked Analysis for Large Contracts

When a contract exceeds the Vik's Rule limit, the tool automatically splits it into overlapping chunks and analyzes each one independently:

  1. Smart splitting — text is divided at paragraph boundaries (double newline), then sentence boundaries, preserving semantic units.
  2. 10% overlap — consecutive chunks overlap by 10% (CHUNK_OVERLAP_FRACTION) to avoid losing context at boundaries.
  3. Per-chunk analysis — each chunk is sent to the LLM with the same prompt, annotated as [Chunk N of M].
  4. LLM synthesis — a final synthesis call merges all per-chunk answers into a single coherent response, deduplicating and reconciling information.

Contracts that fit within the limit are processed in a single call (no chunking overhead).

6. Project Structure

  • Contract_Analysis.py: Main application logic.
  • auth.py: Authentication handlers for Azure and Google.
  • LOI_Contract_prompts.yaml, Customer_prompts.yaml, Employment_prompts.yaml, Supplier_prompts.yaml, Manufacturing_Supply_Chain_prompts.yaml, Retail_Channel_Agreement_prompts.yaml: Analysis questions configuration for different contract types.
  • requirements.txt: Python dependencies.
  • Contracts/: Default input directory.

7. Building the Executable

You can create a standalone executable of the application using PyInstaller.

  1. Install PyInstaller:

    pip install pyinstaller
  2. Build the Executable:

    pyinstaller --onefile Contract_Analysis.py

    This command will generate a single executable file in the dist folder.

Troubleshooting

  • Tesseract Not Found: Ensure Tesseract is installed and added to PATH. You may need to restart your terminal/IDE.
  • Azure Auth Errors: Try running az login in your terminal if using RBAC.
  • Google Auth Errors: Ensure GOOGLE_API_KEY is set correctly.
  • PDF Extraction Issues: If OCR fails, check the logs for Poppler/Tesseract errors.
  • Legacy .doc Files with .docx Extension: Some older Word documents use the legacy OLE2 format but have a .docx extension. The tool auto-detects these and uses Word COM automation. If you see COM attempt warnings in the log, this is normal — the tool retries up to 3 times to handle transient COM lifecycle issues.
  • Long File Paths on Windows: The tool automatically applies the \\?\ extended-length path prefix. If you still encounter path-related errors, ensure you are running Python 3.6+ and consider enabling the Windows long-path registry setting (LongPathsEnabled).

About

AI Power Contract Analysis tool for Supplier Contracts, Customer Contracts, Employment Contracts, Letters of Intent and term sheets

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages