> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Creating a New Project Fake Data Generator

> Guide to building a Python project that generates CSV fake data from a local Ollama model, including venv setup, modular code, API request utility, dependencies, and gitignore

In this guide you'll create a small Python project that generates fake CSV data by querying a local Ollama model. The lesson covers:

* Creating a project folder and a Python virtual environment
* Scaffolding a minimal application and organizing code into modules
* Adding a utility that calls a local Ollama server to produce CSV-formatted fake data
* Capturing dependencies in `requirements.txt`
* Creating a `.gitignore` to keep the repo clean

This walkthrough is optimized for clarity and searchability with actionable commands, code examples, and links to relevant tools and docs.

Overview of steps:

* Create project folder and virtual environment
* Scaffold `main.py` and a `FakeDataGenerator` class
* Move the class to `fake_data_generator.py` and import it from `main.py`
* Add `create_fake_data.py` to call a local Ollama server and save CSV
* Install dependencies and produce `requirements.txt`
* Create a `.gitignore` to exclude the virtual environment and other artifacts

References:

* Python virtual environments: [https://docs.python.org/3/tutorial/venv.html](https://docs.python.org/3/tutorial/venv.html)
* Requests library: [https://docs.python-requests.org/](https://docs.python-requests.org/)
* Ollama docs: [https://docs.ollama.ai](https://docs.ollama.ai)
* GitHub Copilot: [https://github.com/features/copilot](https://github.com/features/copilot)
* VS Code: [https://code.visualstudio.com](https://code.visualstudio.com)

***

## Quick file summary

| File                     | Purpose                                                      |
| ------------------------ | ------------------------------------------------------------ |
| `main.py`                | Minimal entrypoint that runs the generator                   |
| `fake_data_generator.py` | `FakeDataGenerator` class implementation                     |
| `create_fake_data.py`    | Calls a local Ollama model and writes CSV to `fake_data.csv` |
| `requirements.txt`       | Project dependencies captured via `pip freeze`               |
| `.gitignore`             | Exclude virtual env, build artifacts, IDE files              |

***

## 1) Create the project folder and virtual environment

Create the project folder, open it in your editor (e.g., VS Code), and create a Python virtual environment.

Example CLI commands:

```bash theme={null}
mkdir FakeDataGenerator
cd FakeDataGenerator
code .
python3 -m venv .venv
```

Activate the virtual environment:

* macOS / Linux:

```bash theme={null}
source .venv/bin/activate
```

* Windows (PowerShell):

```powershell theme={null}
.venv\Scripts\Activate.ps1
```

When activated your prompt will indicate the venv, for example:

```bash theme={null}
(.venv) jeremy@Jeremys-Mac-Studio FakeDataGenerator %
```

<Callout icon="lightbulb" color="#1CB2FE">
  Use `python3 -m venv .venv` to create a portable local environment. Always activate it before installing project dependencies so packages are isolated to this project.
</Callout>

***

## 2) Scaffold a minimal application

Start with a simple `main.py` that defines a `FakeDataGenerator` class and runs when executed. This keeps the initial project minimal and testable.

`main.py`:

```python theme={null}
# main.py
import sys

class FakeDataGenerator:
    """
    A class to generate fake data.
    """

    def run(self) -> None:
        """
        Runs the fake data generator.
        """
        print("Fake data generator is running...")


def main() -> None:
    """
    Main function to run the FakeDataGenerator.
    """
    generator = FakeDataGenerator()
    generator.run()


if __name__ == "__main__":
    main()
```

Run it to verify:

```bash theme={null}
(.venv) jeremy@Jeremys-Mac-Studio FakeDataGenerator % python main.py
Fake data generator is running...
```

***

## 3) Move the generator into its own module

As projects grow, keeping classes and functions in focused modules improves maintainability. Move `FakeDataGenerator` into `fake_data_generator.py` and import it from `main.py`.

`fake_data_generator.py`:

```python theme={null}
# fake_data_generator.py
class FakeDataGenerator:
    """
    A class to generate fake data.
    """

    def run(self) -> None:
        """
        Runs the fake data generator.
        """
        print("Fake data generator is running...")
```

Update `main.py` to import the class:

```python theme={null}
# main.py
from fake_data_generator import FakeDataGenerator

def main() -> None:
    """
    Main function to run the FakeDataGenerator.
    """
    generator = FakeDataGenerator()
    generator.run()

if __name__ == "__main__":
    main()
```

Run again to confirm behavior remains the same:

```bash theme={null}
(.venv) jeremy@Jeremys-Mac-Studio FakeDataGenerator % python main.py
Fake data generator is running...
```

***

## 4) Add a utility to request fake data from a local Ollama model

Create `create_fake_data.py`. It sends a prompt to an Ollama server running locally at `http://localhost:11434/api/generate`, asks for CSV-formatted fake data, and saves the returned raw CSV text to `fake_data.csv`.

`create_fake_data.py`:

```python theme={null}
# create_fake_data.py
from typing import Any, Dict, Optional
import requests

def create_ollama_prompt() -> str:
    """
    Returns:
        str: Formatted prompt for the model.
    """
    return """Generate fake data for 5 people in CSV format with these columns:
first_name,last_name,email_address,age,city,occupation
Please only return the raw CSV data without any additional text."""

def call_ollama_api(prompt: str) -> Optional[Dict[str, Any]]:
    """
    Sends a prompt to the Ollama API and returns the parsed JSON response.

    Args:
        prompt (str): The prompt to send to the model.

    Returns:
        Optional[Dict[str, Any]]: API response JSON or None on error.
    """
    url = "http://localhost:11434/api/generate"
    payload = {
        "model": "phi4:latest",
        "prompt": prompt,
        "stream": False
    }

    try:
        response = requests.post(url, json=payload)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error calling Ollama API: {e}")
        return None

def main() -> None:
    """
    Main function to generate fake data and save to CSV.
    """
    prompt = create_ollama_prompt()
    response = call_ollama_api(prompt)

    # The exact response schema may vary depending on Ollama server version.
    # This example assumes the server returns a key named 'response' containing raw CSV text.
    if response and "response" in response:
        output_file = "fake_data.csv"
        with open(output_file, "w", newline="") as f:
            f.write(response["response"])
        print(f"Fake data has been saved to {output_file}")
    else:
        print("Failed to generate fake data or unexpected response format")

if __name__ == "__main__":
    main()
```

<Callout icon="warning" color="#FF6B6B">
  Ollama's JSON schema can change across versions. If the server returns fields like `output` or nested objects, inspect the raw JSON and update the key access accordingly before writing to disk.
</Callout>

Install `requests` in the virtual environment:

```bash theme={null}
(.venv) jeremy@Jeremys-Mac-Studio FakeDataGenerator % pip install requests
```

Run the script:

```bash theme={null}
(.venv) jeremy@Jeremys-Mac-Studio FakeDataGenerator % python create_fake_data.py
Fake data has been saved to fake_data.csv
```

Sample generated CSV (example):

```text theme={null}
first_name,last_name,email_address,age,city,occupation
John,Doe,john.doe@example.com,28,New York,Software Engineer
Jane,Smith,jane.smith@example.com,34,San Francisco,Data Scientist
Emily,Jones,emily.jones@example.com,27,Boston,Graphic Designer
Michael,Taylor,michael.taylor@example.com,40,Chicago,Lawyer
Sarah,Garcia,sarah.garcia@example.com,31,Austin,Marketing Manager
```

***

## 5) Track project dependencies with requirements.txt

After installing project packages (for example, `requests`), capture them in `requirements.txt` so collaborators can recreate your environment.

Example:

```bash theme={null}
(.venv) jeremy@Jeremys-Mac-Studio FakeDataGenerator % pip freeze
certifi==2024.12.14
charset-normalizer==3.4.1
idna==3.10
requests==2.32.3
urllib3==2.3.0

(.venv) jeremy@Jeremys-Mac-Studio FakeDataGenerator % pip freeze > requirements.txt
```

Recreate the environment from `requirements.txt`:

```bash theme={null}
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
```

***

## 6) Create a robust .gitignore

Exclude the virtual environment directory and other generated artifacts from Git. Below is a practical `.gitignore` example to keep your repository clean.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/DEYrDKSldd3lYPoS/images/GitHub-Copilot-in-Action/Using-Copilot-Efficiently/Creating-a-New-Project-Fake-Data-Generator/gitignore-exclude-venv-chat-screenshot.jpg?fit=max&auto=format&n=DEYrDKSldd3lYPoS&q=85&s=1228c5acae67767c2ae80187def6ba97" alt="A dark-themed code editor/chat screenshot showing a user asking how to keep git from seeing a .venv folder. GitHub Copilot is generating a reply that suggests creating a .gitignore file to exclude the virtual environment." width="1920" height="1080" data-path="images/GitHub-Copilot-in-Action/Using-Copilot-Efficiently/Creating-a-New-Project-Fake-Data-Generator/gitignore-exclude-venv-chat-screenshot.jpg" />
</Frame>

Example `.gitignore` (partial):

```text theme={null}
# Virtual Environment
.venv/
venv/
ENV/
env/

# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
dist/
*.egg-info/

# IDE
.idea/
.vscode/
*.swp
.DS_Store
```

If your `.venv` was already committed, remove it from tracking:

```bash theme={null}
git rm -r --cached .venv
git commit -m "Remove .venv from git tracking"
```

Then add and commit the `.gitignore`:

```bash theme={null}
git add .gitignore
git commit -m "Add .gitignore file"
```

***

## Summary

* Created a new Python project with an isolated virtual environment.
* Scaffoled a minimal `FakeDataGenerator` and moved it into a dedicated module.
* Built `create_fake_data.py` to call a local Ollama model and save CSV-formatted fake data.
* Captured dependencies in `requirements.txt` and protected the repo with `.gitignore`.
* This example demonstrates how GitHub Copilot can accelerate boilerplate creation; future articles will show importing generated data into a database and using it for more advanced workflows.

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/github-copilot-in-action/module/5c3827f4-b200-4c22-90bb-e7c6540d96d8/lesson/d6c93d07-7c40-4bc5-aadc-c2ba049145fd" />
</CardGroup>
