PYTHON FOR AI • LESSON 6

AI Application Project

In this project, we will combine the Python skills learned in this lesson to build a small AI-style document processing application. The application will read a document, process its information, store the result as JSON, and use environment variables and logging like a real application.

CORE IDEA

A real AI application is a combination of smaller Python concepts.

Instead of learning each concept separately, this project connects environment variables, logging, type hints, file processing, JSON, and application structure into one practical workflow.

01

Project Goal

We will build a simple AI Document Analyzer.

The application will:

  • Read a text document.
  • Clean the document text.
  • Calculate basic information.
  • Create a structured result.
  • Save the result as JSON.
  • Use an environment variable for configuration.
  • Write useful information to a log file.
User
  ↓
Text Document
  ↓
Python Application
  ↓
Read File
  ↓
Process Text
  ↓
Create Result
  ↓
Save JSON
  ↓
AI-ready Data
02

Project Structure

Start with this project structure:

ai-document-analyzer/
│
├── main.py
├── .env
│
├── documents/
│   └── article.txt
│
├── output/
│
└── logs/
    └── app.log

Each part has a clear responsibility.

  • main.py → application entry point
  • .env → configuration values
  • documents/ → input documents
  • output/ → generated JSON
  • logs/ → application logs
03

Create the Input Document

Create:

documents/article.txt

Put this content inside it:

Python is a popular programming language.

Python is widely used in artificial intelligence,
machine learning, data science, and web development.

AI applications can use Python to process data,
communicate with APIs, and work with machine learning models.
04

Add Environment Variables

Create a .env file:

APP_NAME=AI Document Analyzer
ENVIRONMENT=development

Environment variables allow configuration to stay outside the Python source code.

This becomes especially important when an application later needs API keys or other sensitive configuration.

Install python-dotenv:

pip install python-dotenv
05

Add Logging

Logging lets us understand what our application is doing while it runs.

Instead of relying only on print(), we will write important events to a log file.

import logging


logging.basicConfig(
    filename="logs/app.log",
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s"
)


logging.info("Application started")

For example, the log could contain:

2026-08-19 10:30:12 - INFO - Application started
2026-08-19 10:30:12 - INFO - Document loaded
2026-08-19 10:30:12 - INFO - Analysis completed
06

Add Type Hints

Type hints make the purpose of functions and variables easier to understand.

For example:

def count_words(text: str) -> int:

    return len(text.split())

This tells us:

  • text should be a string.
  • The function returns an integer.
07

Read the Document

Now we need a function that reads our document.

from pathlib import Path


def read_document(file_path: Path) -> str:

    return file_path.read_text(
        encoding="utf-8"
    )

This keeps file reading separate from the rest of the application logic.

08

Process the Text

We can create a function that removes unnecessary whitespace.

def clean_text(text: str) -> str:

    return " ".join(
        text.split()
    )

For example:

Before:

Python is a popular programming language.


After:

Python is a popular programming language.
09

Analyze the Document

Now create a function that extracts useful information from the text.

def analyze_text(text: str) -> dict:

    words = text.split()

    return {
        "character_count": len(text),
        "word_count": len(words),
        "line_count": len(text.splitlines())
    }

For the moment, this is basic text analysis rather than an actual AI model. That is intentional.

First understand the application pipeline. An AI model can be added later.

10

Save the Result as JSON

We can save our analysis in a structured JSON file.

import json


def save_result(
    result: dict,
    output_path: Path
) -> None:

    with open(
        output_path,
        "w",
        encoding="utf-8"
    ) as file:

        json.dump(
            result,
            file,
            indent=4
        )

The generated JSON might look like:

{
    "character_count": 247,
    "word_count": 42,
    "line_count": 5
}
11

Build the Complete Application

Now combine everything into main.py.

import json
import logging
import os
from pathlib import Path

from dotenv import load_dotenv


# Load environment variables

load_dotenv()


# Create directories

Path("output").mkdir(
    exist_ok=True
)

Path("logs").mkdir(
    exist_ok=True
)


# Configure logging

logging.basicConfig(
    filename="logs/app.log",
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s"
)


def read_document(
    file_path: Path
) -> str:

    return file_path.read_text(
        encoding="utf-8"
    )


def clean_text(
    text: str
) -> str:

    return " ".join(
        text.split()
    )


def analyze_text(
    text: str
) -> dict:

    words = text.split()

    return {
        "character_count": len(text),
        "word_count": len(words),
        "line_count": len(
            text.splitlines()
        )
    }


def save_result(
    result: dict,
    output_path: Path
) -> None:

    with open(
        output_path,
        "w",
        encoding="utf-8"
    ) as file:

        json.dump(
            result,
            file,
            indent=4
        )


def main() -> None:

    app_name = os.getenv(
        "APP_NAME",
        "AI Document Analyzer"
    )

    logging.info(
        "%s started",
        app_name
    )

    input_file = Path(
        "documents/article.txt"
    )

    output_file = Path(
        "output/result.json"
    )

    if not input_file.exists():

        logging.error(
            "Input document not found"
        )

        print(
            "Document not found"
        )

        return

    try:

        logging.info(
            "Reading document"
        )

        text = read_document(
            input_file
        )

        logging.info(
            "Cleaning document"
        )

        cleaned_text = clean_text(
            text
        )

        logging.info(
            "Analyzing document"
        )

        result = analyze_text(
            cleaned_text
        )

        save_result(
            result,
            output_file
        )

        logging.info(
            "Analysis completed"
        )

        print(
            "Document analyzed successfully"
        )

        print(
            json.dumps(
                result,
                indent=4
            )
        )

    except Exception as error:

        logging.exception(
            "Application failed: %s",
            error
        )

        print(
            "Something went wrong"
        )


if __name__ == "__main__":

    main()
12

Run the Project

From the project directory, run:

python main.py

You should see something similar to:

Document analyzed successfully

{
    "character_count": 247,
    "word_count": 42,
    "line_count": 5
}

A new file will also be created:

output/result.json
13

Understand the Complete Flow

Don't just copy the code. Understand what happens when the program runs.

main()
   ↓
Load .env
   ↓
Configure logging
   ↓
Check document
   ↓
Read article.txt
   ↓
Clean text
   ↓
Analyze text
   ↓
Create Python dictionary
   ↓
Convert dictionary to JSON
   ↓
Save result.json
   ↓
Log completion
14

Where Does the AI Actually Fit?

The project so far prepares the application around the AI model. The actual model can be inserted after the document has been read and cleaned.

Document
   ↓
Read
   ↓
Clean
   ↓
AI Model
   ↓
AI Response
   ↓
JSON
   ↓
Save / Return to User

For example, you could send the cleaned document to an AI model with a prompt such as:

prompt = f"""
Summarize the following document
in three short points:

{cleaned_text}
"""

The model's response could then be stored in the JSON result.

15

Example AI-Ready JSON

A real application could eventually produce something like:

{
    "document": "article.txt",
    "word_count": 42,
    "summary": [
        "Python is widely used in AI.",
        "Python is useful for processing data.",
        "Python can communicate with AI APIs."
    ]
}

Now the result is structured and can easily be returned through an API, stored in a database, or displayed in a frontend application.

16

Where Async Python Can Be Added

If the application needs to call an external AI API, that network request can be asynchronous.

The important distinction is:

File processing
      ↓
Usually simple synchronous code


AI API request
      ↓
Can benefit from async


Multiple API requests
      ↓
Async becomes more useful

Don't make everything async just because the project uses AI. Use async when there is actual I/O waiting or concurrency to gain.

17

How This Becomes a Real AI Application

The project is intentionally small. A production application would normally have more components.

User uploads PDF
       ↓
Backend receives file
       ↓
Extract text
       ↓
Clean text
       ↓
Send text to AI model
       ↓
Receive AI response
       ↓
Store result
       ↓
Return response to frontend

Examples of applications built using this basic idea include:

  • Document summarizers
  • PDF question-answering applications
  • Resume analyzers
  • Customer feedback analyzers
  • AI content classification systems
18

Possible Improvements

Once the basic version works, improve it step by step.

  • Add PDF file support.
  • Add CSV processing.
  • Add an AI API.
  • Add asynchronous API requests.
  • Add better error handling.
  • Store results in a database.
  • Create a REST API around the application.
  • Build a frontend for uploading documents.

Do not start with all of these at once. Build the smallest working version first, then add one feature at a time.

19

What You Used From This Lesson

Environment Variables
        ↓
python-dotenv


Logging
        ↓
logging


Type Hints
        ↓
Function annotations


File Processing
        ↓
pathlib


JSON
        ↓
json


Async Python
        ↓
Useful when adding external API calls

This is the important part of the project: you are no longer learning these concepts in isolation. You are combining them to build an application.

20

What You Learned

  • How to structure a small Python AI application.
  • How to process a document.
  • How to use environment variables.
  • How to add application logging.
  • How to use type hints.
  • How to process files with pathlib.
  • How to generate JSON results.
  • How the AI model fits into the application flow.
  • When async programming can be useful.
  • How individual Python concepts work together.
KEY TAKEAWAY

Building AI applications is not just about calling an AI model.

A useful AI application needs normal software engineering around the model: configuration, file processing, validation, logging, structured data, error handling, and API communication. Once you understand this foundation, adding an AI model becomes one part of a larger application instead of the entire application.