fakex 0.2.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fakex/__init__.py +35 -0
- fakex/__main__.py +6 -0
- fakex/async_engine.py +168 -0
- fakex/cli/__init__.py +6 -0
- fakex/cli/app.py +186 -0
- fakex/cli/display.py +72 -0
- fakex/engine.py +136 -0
- fakex/exporters/__init__.py +8 -0
- fakex/exporters/csv_exporter.py +62 -0
- fakex/exporters/json_exporter.py +27 -0
- fakex/exporters/sqlite_exporter.py +131 -0
- fakex/gui.py +1438 -0
- fakex/locales/__init__.py +17 -0
- fakex/locales/base.py +61 -0
- fakex/locales/bd.py +118 -0
- fakex/locales/gb.py +127 -0
- fakex/locales/in_locale.py +127 -0
- fakex/locales/registry.py +150 -0
- fakex/models.py +74 -0
- fakex/photos/__init__.py +8 -0
- fakex/photos/cropper.py +62 -0
- fakex/photos/fetcher.py +172 -0
- fakex/photos/providers.py +79 -0
- fakex-0.2.1.dist-info/METADATA +434 -0
- fakex-0.2.1.dist-info/RECORD +28 -0
- fakex-0.2.1.dist-info/WHEEL +4 -0
- fakex-0.2.1.dist-info/entry_points.txt +2 -0
- fakex-0.2.1.dist-info/licenses/LICENSE +21 -0
fakex/__init__.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Fakex - The Ultimate Mock Persona & Bio-Data Generator."""
|
|
2
|
+
|
|
3
|
+
from fakex.async_engine import AsyncFakex
|
|
4
|
+
from fakex.engine import Fakex
|
|
5
|
+
from fakex.exporters import export_csv, export_json, export_sqlite
|
|
6
|
+
from fakex.models import (
|
|
7
|
+
Address,
|
|
8
|
+
Contact,
|
|
9
|
+
GenderEnum,
|
|
10
|
+
Persona,
|
|
11
|
+
PhotoDetails,
|
|
12
|
+
PhotoProviderEnum,
|
|
13
|
+
ProfessionalBio,
|
|
14
|
+
)
|
|
15
|
+
from fakex.photos.cropper import crop_to_circle
|
|
16
|
+
|
|
17
|
+
__version__ = "0.2.1"
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"Address",
|
|
21
|
+
"AsyncFakex",
|
|
22
|
+
"Contact",
|
|
23
|
+
"Fakex",
|
|
24
|
+
"GenderEnum",
|
|
25
|
+
"Persona",
|
|
26
|
+
"PhotoDetails",
|
|
27
|
+
"PhotoProviderEnum",
|
|
28
|
+
"ProfessionalBio",
|
|
29
|
+
"__version__",
|
|
30
|
+
"crop_to_circle",
|
|
31
|
+
"export_csv",
|
|
32
|
+
"export_json",
|
|
33
|
+
"export_sqlite",
|
|
34
|
+
]
|
|
35
|
+
|
fakex/__main__.py
ADDED
fakex/async_engine.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Asynchronous generation engine for high-speed concurrent batching."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import random
|
|
5
|
+
import uuid
|
|
6
|
+
from datetime import date, timedelta
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
from faker import Faker
|
|
11
|
+
|
|
12
|
+
from fakex.locales.registry import LocaleRegistry
|
|
13
|
+
from fakex.models import Persona, PhotoDetails, PhotoProviderEnum
|
|
14
|
+
from fakex.photos.fetcher import PhotoFetcher
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class AsyncFakex:
|
|
18
|
+
"""Asynchronous persona generator engineered for non-blocking I/O and batch downloads."""
|
|
19
|
+
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
locale: str = "en_US",
|
|
23
|
+
seed: int | None = None,
|
|
24
|
+
max_connections: int = 20,
|
|
25
|
+
timeout: float = 10.0,
|
|
26
|
+
):
|
|
27
|
+
self.locale = locale
|
|
28
|
+
# HIGH-03: Guard against invalid Faker locale — fallback to en_US with a warning
|
|
29
|
+
try:
|
|
30
|
+
self.faker = Faker(locale=locale)
|
|
31
|
+
except (AttributeError, ValueError) as exc:
|
|
32
|
+
print(f"[AsyncFakex] Warning: Invalid locale '{locale}' ({exc}). Falling back to 'en_US'.")
|
|
33
|
+
self.locale = "en_US"
|
|
34
|
+
self.faker = Faker(locale="en_US")
|
|
35
|
+
self.rng = random.Random(seed)
|
|
36
|
+
if seed is not None:
|
|
37
|
+
self.faker.seed_instance(seed)
|
|
38
|
+
self.provider = LocaleRegistry.get_provider(self.locale, self.faker, rng=self.rng)
|
|
39
|
+
self.max_connections = max_connections
|
|
40
|
+
self.timeout = timeout
|
|
41
|
+
|
|
42
|
+
def _calculate_birthdate(self, min_age: int, max_age: int) -> tuple[date, int]:
|
|
43
|
+
# CRIT-03: Swap inverted range; clamp to [0, 120]
|
|
44
|
+
lower = min(120, max(0, min(min_age, max_age)))
|
|
45
|
+
upper = min(120, max(0, max(min_age, max_age)))
|
|
46
|
+
age = self.rng.randint(lower, upper)
|
|
47
|
+
days_in_year = 365
|
|
48
|
+
offset_days = self.rng.randint(0, 364)
|
|
49
|
+
birthdate = date.today() - timedelta(days=(age * days_in_year) + offset_days)
|
|
50
|
+
return birthdate, age
|
|
51
|
+
|
|
52
|
+
def _create_unhydrated_persona(self, gender: str, age_range: tuple[int, int]) -> Persona:
|
|
53
|
+
# MED-03: Accept None/empty gender gracefully
|
|
54
|
+
resolved_gender = (gender or "random").lower().strip()
|
|
55
|
+
if resolved_gender not in ("male", "female"):
|
|
56
|
+
resolved_gender = self.rng.choice(["male", "female"])
|
|
57
|
+
|
|
58
|
+
first_name, last_name, full_name = self.provider.generate_name(resolved_gender)
|
|
59
|
+
birthdate, age = self._calculate_birthdate(age_range[0], age_range[1])
|
|
60
|
+
address = self.provider.generate_address()
|
|
61
|
+
contact = self.provider.generate_contact(first_name, last_name)
|
|
62
|
+
bio = self.provider.generate_bio()
|
|
63
|
+
|
|
64
|
+
return Persona(
|
|
65
|
+
id=str(uuid.uuid4()),
|
|
66
|
+
first_name=first_name,
|
|
67
|
+
last_name=last_name,
|
|
68
|
+
full_name=full_name,
|
|
69
|
+
gender=resolved_gender.lower(),
|
|
70
|
+
birthdate=birthdate,
|
|
71
|
+
age=age,
|
|
72
|
+
address=address,
|
|
73
|
+
contact=contact,
|
|
74
|
+
bio=bio,
|
|
75
|
+
photo=None
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
async def generate_persona(
|
|
79
|
+
self,
|
|
80
|
+
gender: str = "random",
|
|
81
|
+
age_range: tuple[int, int] = (18, 65),
|
|
82
|
+
photo_source: str = "none",
|
|
83
|
+
download_dir: Path | str = "./downloads/photos",
|
|
84
|
+
crop_circle: bool = False,
|
|
85
|
+
) -> Persona:
|
|
86
|
+
"""Asynchronously generate a single validated Persona instance (DEF-05)."""
|
|
87
|
+
persona = self._create_unhydrated_persona(gender, age_range)
|
|
88
|
+
|
|
89
|
+
if photo_source.lower() not in ("none", "", PhotoProviderEnum.NONE.value):
|
|
90
|
+
fetcher = PhotoFetcher(
|
|
91
|
+
download_dir=download_dir,
|
|
92
|
+
timeout=self.timeout,
|
|
93
|
+
max_connections=self.max_connections,
|
|
94
|
+
)
|
|
95
|
+
limits = httpx.Limits(max_connections=self.max_connections, max_keepalive_connections=self.max_connections)
|
|
96
|
+
async with httpx.AsyncClient(limits=limits, timeout=self.timeout) as client:
|
|
97
|
+
photo_res = await fetcher.fetch_photo_async(
|
|
98
|
+
client=client,
|
|
99
|
+
provider=photo_source,
|
|
100
|
+
gender=persona.gender,
|
|
101
|
+
persona_id=persona.id[:8],
|
|
102
|
+
)
|
|
103
|
+
if isinstance(photo_res, PhotoDetails):
|
|
104
|
+
if crop_circle and photo_res.local_path:
|
|
105
|
+
try:
|
|
106
|
+
from fakex.photos.cropper import crop_to_circle
|
|
107
|
+
photo_res.local_path = crop_to_circle(photo_res.local_path)
|
|
108
|
+
# Optional avatar conversion must retain the downloaded original on failure.
|
|
109
|
+
except Exception: # noqa: BLE001, S110
|
|
110
|
+
pass
|
|
111
|
+
persona.photo = photo_res
|
|
112
|
+
|
|
113
|
+
return persona
|
|
114
|
+
|
|
115
|
+
async def generate_batch(
|
|
116
|
+
self,
|
|
117
|
+
count: int,
|
|
118
|
+
gender: str = "random",
|
|
119
|
+
age_range: tuple[int, int] = (18, 65),
|
|
120
|
+
photo_source: str = "none",
|
|
121
|
+
download_dir: Path | str = "./downloads/photos",
|
|
122
|
+
crop_circle: bool = False,
|
|
123
|
+
) -> list[Persona]:
|
|
124
|
+
"""Concurrently generate personas and download profile photos."""
|
|
125
|
+
personas = [self._create_unhydrated_persona(gender, age_range) for _ in range(count)]
|
|
126
|
+
|
|
127
|
+
if photo_source.lower() in ("none", "", PhotoProviderEnum.NONE.value):
|
|
128
|
+
return personas
|
|
129
|
+
|
|
130
|
+
fetcher = PhotoFetcher(
|
|
131
|
+
download_dir=download_dir,
|
|
132
|
+
timeout=self.timeout,
|
|
133
|
+
max_connections=self.max_connections
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
limits = httpx.Limits(max_connections=self.max_connections, max_keepalive_connections=self.max_connections)
|
|
137
|
+
async with httpx.AsyncClient(limits=limits, timeout=self.timeout) as client:
|
|
138
|
+
semaphore = asyncio.Semaphore(self.max_connections)
|
|
139
|
+
|
|
140
|
+
async def download_worker(persona: Persona) -> PhotoDetails:
|
|
141
|
+
async with semaphore:
|
|
142
|
+
return await fetcher.fetch_photo_async(
|
|
143
|
+
client=client,
|
|
144
|
+
provider=photo_source,
|
|
145
|
+
gender=persona.gender,
|
|
146
|
+
persona_id=persona.id[:8]
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
# HIGH-02: Chunked batch execution (chunks of 50) prevents coroutine explosion on large batches
|
|
150
|
+
chunk_size = 50
|
|
151
|
+
for i in range(0, len(personas), chunk_size):
|
|
152
|
+
chunk = personas[i : i + chunk_size]
|
|
153
|
+
tasks = [download_worker(p) for p in chunk]
|
|
154
|
+
photo_results = await asyncio.gather(*tasks, return_exceptions=True)
|
|
155
|
+
|
|
156
|
+
for persona, photo_res in zip(chunk, photo_results):
|
|
157
|
+
if isinstance(photo_res, PhotoDetails):
|
|
158
|
+
if crop_circle and photo_res.local_path:
|
|
159
|
+
try:
|
|
160
|
+
from fakex.photos.cropper import crop_to_circle
|
|
161
|
+
photo_res.local_path = crop_to_circle(photo_res.local_path)
|
|
162
|
+
# Optional avatar conversion must retain the downloaded original on failure.
|
|
163
|
+
except Exception: # noqa: BLE001, S110
|
|
164
|
+
pass
|
|
165
|
+
persona.photo = photo_res
|
|
166
|
+
|
|
167
|
+
return personas
|
|
168
|
+
|
fakex/cli/__init__.py
ADDED
fakex/cli/app.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""Main Typer CLI application for Fakex."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
import typer
|
|
8
|
+
from rich.progress import (
|
|
9
|
+
BarColumn,
|
|
10
|
+
Progress,
|
|
11
|
+
SpinnerColumn,
|
|
12
|
+
TaskProgressColumn,
|
|
13
|
+
TextColumn,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
from fakex import __version__
|
|
17
|
+
from fakex.async_engine import AsyncFakex
|
|
18
|
+
from fakex.cli.display import console, render_preview_table
|
|
19
|
+
from fakex.engine import Fakex
|
|
20
|
+
from fakex.exporters import export_csv, export_json, export_sqlite
|
|
21
|
+
|
|
22
|
+
app = typer.Typer(
|
|
23
|
+
name="fakex",
|
|
24
|
+
help="🎭 The Ultimate Mock Persona & Bio-Data Generator",
|
|
25
|
+
add_completion=False,
|
|
26
|
+
context_settings={"help_option_names": ["-h", "--help"]},
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def version_callback(value: bool):
|
|
31
|
+
"""Callback for top-level --version and -v flags (BUG-15)."""
|
|
32
|
+
if value:
|
|
33
|
+
console.print(f"[bold cyan]Fakex[/bold cyan] version [bold green]{__version__}[/bold green] 🎭⚡")
|
|
34
|
+
raise typer.Exit()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@app.callback()
|
|
38
|
+
def main(
|
|
39
|
+
# Retain Optional for the declared Typer >=0.9 compatibility range.
|
|
40
|
+
version: Optional[bool] = typer.Option( # noqa: UP045
|
|
41
|
+
None,
|
|
42
|
+
"--version",
|
|
43
|
+
"-v",
|
|
44
|
+
help="Show Fakex version and exit.",
|
|
45
|
+
callback=version_callback,
|
|
46
|
+
is_eager=True,
|
|
47
|
+
),
|
|
48
|
+
):
|
|
49
|
+
"""🎭 Fakex - The Ultimate Mock Persona & Bio-Data Generator."""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@app.command(name="version")
|
|
53
|
+
def version_command():
|
|
54
|
+
"""Print Fakex version and engine info."""
|
|
55
|
+
console.print(f"[bold cyan]Fakex[/bold cyan] version [bold green]{__version__}[/bold green] 🎭⚡")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@app.command(name="gui")
|
|
59
|
+
def gui_command():
|
|
60
|
+
"""Launch the interactive Fakex Studio Desktop GUI."""
|
|
61
|
+
console.print("[bold green]Starting Fakex Studio GUI...[/bold green] 🎭")
|
|
62
|
+
try:
|
|
63
|
+
from fakex.gui import main as launch_gui
|
|
64
|
+
launch_gui()
|
|
65
|
+
# GUI launch is an optional CLI boundary; report every launch failure as before.
|
|
66
|
+
except Exception as e: # noqa: BLE001
|
|
67
|
+
console.print(f"[bold red]Failed to launch GUI:[/bold red] {e}")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@app.command(name="locales")
|
|
71
|
+
def locales_command():
|
|
72
|
+
"""List recommended and supported locales."""
|
|
73
|
+
console.print("[bold yellow]Supported Key Locales:[/bold yellow]")
|
|
74
|
+
console.print(" • [bold cyan]bn_BD[/bold cyan]: Bangladesh (Custom operator prefixes, real division/postal codes)")
|
|
75
|
+
console.print(" • [bold cyan]en_US[/bold cyan]: United States")
|
|
76
|
+
console.print(" • [bold cyan]en_GB[/bold cyan]: United Kingdom")
|
|
77
|
+
console.print(" • [bold cyan]hi_IN[/bold cyan]: India")
|
|
78
|
+
console.print(" • [bold cyan]de_DE[/bold cyan]: Germany")
|
|
79
|
+
console.print(" • [bold cyan]ja_JP[/bold cyan]: Japan")
|
|
80
|
+
console.print(" • Any valid Faker locale code is supported.\n")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@app.command(name="generate")
|
|
84
|
+
def generate_command(
|
|
85
|
+
count: int = typer.Option(1, "--count", "-c", help="Total personas to generate"),
|
|
86
|
+
locale: str = typer.Option("en_US", "--locale", "-l", help="Locale code (e.g. bn_BD, en_US)"),
|
|
87
|
+
gender: str = typer.Option("random", "--gender", "-g", help="Gender filter (male/female/random)"),
|
|
88
|
+
min_age: int = typer.Option(18, "--min-age", help="Minimum age"),
|
|
89
|
+
max_age: int = typer.Option(65, "--max-age", help="Maximum age"),
|
|
90
|
+
photo: str = typer.Option("none", "--photo", "-p", help="Photo provider (none, real, ai, dice, pravatar)"),
|
|
91
|
+
# Typer requires these OptionInfo defaults to retain the existing CLI contract.
|
|
92
|
+
photo_dir: Path = typer.Option(Path("./downloads/photos"), "--photo-dir", help="Directory to save photos"), # noqa: B008
|
|
93
|
+
output: Optional[Path] = typer.Option(None, "--output", "-o", help="Output file path (.json, .csv, or .sqlite/.db database)"), # noqa: B008, UP045
|
|
94
|
+
preview: bool = typer.Option(True, "--preview/--no-preview", help="Show Rich preview table"),
|
|
95
|
+
crop_circle: bool = typer.Option(False, "--crop-circle", help="Auto-crop downloaded photos into transparent circular PNG avatars"),
|
|
96
|
+
seed: Optional[int] = typer.Option(None, "--seed", "-s", help="Seed for deterministic output"), # noqa: UP045
|
|
97
|
+
):
|
|
98
|
+
"""Generate mock personas with bio-data and optional profile pictures."""
|
|
99
|
+
# 1. Validate count boundary
|
|
100
|
+
if count <= 0:
|
|
101
|
+
console.print("[bold red]Error: --count must be at least 1.[/bold red]")
|
|
102
|
+
raise typer.Exit(code=1)
|
|
103
|
+
|
|
104
|
+
# 2. Normalize and clamp age boundaries
|
|
105
|
+
lower_age = max(0, min(min_age, max_age))
|
|
106
|
+
upper_age = min(120, max(min_age, max_age))
|
|
107
|
+
resolved_age_range = (lower_age, upper_age)
|
|
108
|
+
|
|
109
|
+
# 3. Validate and resolve photo directory
|
|
110
|
+
resolved_photo_dir = Path(photo_dir).expanduser().resolve()
|
|
111
|
+
|
|
112
|
+
# 4. Validate output path if provided
|
|
113
|
+
resolved_output: Path | None = None
|
|
114
|
+
if output:
|
|
115
|
+
resolved_output = Path(output).expanduser().resolve()
|
|
116
|
+
if resolved_output.is_dir():
|
|
117
|
+
console.print(
|
|
118
|
+
f"[bold red]Error: --output '{output}' is an existing directory. "
|
|
119
|
+
"Please specify a target file path (e.g. personas.json, personas.csv, or personas.sqlite).[/bold red]"
|
|
120
|
+
)
|
|
121
|
+
raise typer.Exit(code=1)
|
|
122
|
+
|
|
123
|
+
console.print(f"[bold green]Starting Fakex Persona Generator[/bold green] (Locale: [cyan]{locale}[/cyan], Count: [magenta]{count}[/magenta])...")
|
|
124
|
+
|
|
125
|
+
with Progress(
|
|
126
|
+
SpinnerColumn(),
|
|
127
|
+
TextColumn("[progress.description]{task.description}"),
|
|
128
|
+
BarColumn(),
|
|
129
|
+
TaskProgressColumn(),
|
|
130
|
+
console=console,
|
|
131
|
+
) as progress:
|
|
132
|
+
task = progress.add_task("[cyan]Generating personas...", total=count)
|
|
133
|
+
|
|
134
|
+
if photo.lower() in ("none", ""):
|
|
135
|
+
# High speed synchronous generation
|
|
136
|
+
engine = Fakex(locale=locale, seed=seed)
|
|
137
|
+
personas = []
|
|
138
|
+
for p in engine.stream_personas(
|
|
139
|
+
count=count,
|
|
140
|
+
gender=gender,
|
|
141
|
+
age_range=resolved_age_range,
|
|
142
|
+
photo_source="none",
|
|
143
|
+
download_dir=resolved_photo_dir,
|
|
144
|
+
crop_circle=crop_circle,
|
|
145
|
+
):
|
|
146
|
+
personas.append(p)
|
|
147
|
+
progress.advance(task, 1)
|
|
148
|
+
else:
|
|
149
|
+
# Async parallel photo downloads (DEF-08: crop_circle passed directly to engine)
|
|
150
|
+
async def run_async():
|
|
151
|
+
afx = AsyncFakex(locale=locale, seed=seed)
|
|
152
|
+
return await afx.generate_batch(
|
|
153
|
+
count=count,
|
|
154
|
+
gender=gender,
|
|
155
|
+
age_range=resolved_age_range,
|
|
156
|
+
photo_source=photo,
|
|
157
|
+
download_dir=resolved_photo_dir,
|
|
158
|
+
crop_circle=crop_circle,
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
personas = asyncio.run(run_async())
|
|
162
|
+
progress.update(task, completed=count)
|
|
163
|
+
|
|
164
|
+
console.print(f"\n[bold green]✔ Successfully generated {len(personas)} persona(s).[/bold green]")
|
|
165
|
+
|
|
166
|
+
# Terminal preview
|
|
167
|
+
if preview and personas:
|
|
168
|
+
render_preview_table(personas, title=f"Fakex Personas ({locale})")
|
|
169
|
+
|
|
170
|
+
# File export
|
|
171
|
+
if resolved_output:
|
|
172
|
+
suffix = resolved_output.suffix.lower()
|
|
173
|
+
if suffix == ".csv":
|
|
174
|
+
saved_path = export_csv(personas, resolved_output)
|
|
175
|
+
console.print(f"[bold cyan]✔ CSV Exported:[/bold cyan] {saved_path}")
|
|
176
|
+
elif suffix in (".db", ".sqlite", ".sqlite3"):
|
|
177
|
+
saved_path = export_sqlite(personas, resolved_output)
|
|
178
|
+
console.print(f"[bold cyan]✔ SQLite Database Seeded:[/bold cyan] {saved_path}")
|
|
179
|
+
else:
|
|
180
|
+
saved_path = export_json(personas, resolved_output)
|
|
181
|
+
console.print(f"[bold cyan]✔ JSON Exported:[/bold cyan] {saved_path}")
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
if __name__ == "__main__":
|
|
185
|
+
app()
|
|
186
|
+
|
fakex/cli/display.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Rich terminal display helpers for Fakex CLI."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
from typing import IO, cast
|
|
5
|
+
|
|
6
|
+
from rich.console import Console
|
|
7
|
+
from rich.table import Table
|
|
8
|
+
|
|
9
|
+
from fakex.models import Persona
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class _EncodingSafeStream:
|
|
13
|
+
"""Escape only characters the underlying text stream cannot encode."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, stream: IO[str]):
|
|
16
|
+
self._stream = stream
|
|
17
|
+
|
|
18
|
+
def __getattr__(self, name: str):
|
|
19
|
+
return getattr(self._stream, name)
|
|
20
|
+
|
|
21
|
+
def write(self, text: str) -> int:
|
|
22
|
+
encoding = self._stream.encoding
|
|
23
|
+
if encoding:
|
|
24
|
+
try:
|
|
25
|
+
text.encode(encoding)
|
|
26
|
+
except UnicodeEncodeError:
|
|
27
|
+
text = text.encode(encoding, errors="backslashreplace").decode(encoding)
|
|
28
|
+
return self._stream.write(text)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class _EncodingSafeConsole(Console):
|
|
32
|
+
"""Keep Rich's dynamic stream selection and rendering behavior intact."""
|
|
33
|
+
|
|
34
|
+
@Console.file.getter
|
|
35
|
+
def file(self) -> IO[str]:
|
|
36
|
+
stream = super().file
|
|
37
|
+
if not getattr(stream, "encoding", None):
|
|
38
|
+
return stream
|
|
39
|
+
return cast(IO[str], _EncodingSafeStream(stream))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
console = _EncodingSafeConsole()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def render_preview_table(personas: Sequence[Persona], title: str = "Generated Personas Preview"):
|
|
46
|
+
"""Render a clean, colorful Rich table preview of personas."""
|
|
47
|
+
table = Table(title=title, header_style="bold cyan", border_style="dim")
|
|
48
|
+
|
|
49
|
+
table.add_column("Full Name", style="bold white")
|
|
50
|
+
table.add_column("Gender / Age", style="magenta")
|
|
51
|
+
table.add_column("Phone", style="green")
|
|
52
|
+
table.add_column("Email", style="blue")
|
|
53
|
+
table.add_column("City / Country", style="yellow")
|
|
54
|
+
table.add_column("Job Title", style="cyan")
|
|
55
|
+
table.add_column("Photo Path", style="dim")
|
|
56
|
+
|
|
57
|
+
for p in personas[:10]: # Cap preview at 10 for clean terminal display
|
|
58
|
+
photo_display = str(p.photo.local_path.name) if p.photo and p.photo.local_path else "-"
|
|
59
|
+
table.add_row(
|
|
60
|
+
p.full_name,
|
|
61
|
+
f"{p.gender.capitalize()} ({p.age})",
|
|
62
|
+
p.contact.phone,
|
|
63
|
+
p.contact.email,
|
|
64
|
+
f"{p.address.city}, {p.address.country}",
|
|
65
|
+
p.bio.job_title,
|
|
66
|
+
photo_display
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
console.print(table)
|
|
70
|
+
if len(personas) > 10:
|
|
71
|
+
console.print(f"[dim](... and {len(personas) - 10} more rows)[/dim]\n")
|
|
72
|
+
|
fakex/engine.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""Synchronous generation engine for Fakex."""
|
|
2
|
+
|
|
3
|
+
import random
|
|
4
|
+
import uuid
|
|
5
|
+
from collections.abc import Generator
|
|
6
|
+
from datetime import date, timedelta
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from faker import Faker
|
|
10
|
+
|
|
11
|
+
from fakex.locales.registry import LocaleRegistry
|
|
12
|
+
from fakex.models import Persona, PhotoProviderEnum
|
|
13
|
+
from fakex.photos.fetcher import PhotoFetcher
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Fakex:
|
|
17
|
+
"""Core synchronous persona and bio-data generator."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, locale: str = "en_US", seed: int | None = None):
|
|
20
|
+
self.locale = locale
|
|
21
|
+
# HIGH-03: Guard against invalid Faker locale — fallback to en_US with a warning
|
|
22
|
+
try:
|
|
23
|
+
self.faker = Faker(locale=locale)
|
|
24
|
+
except (AttributeError, ValueError) as exc:
|
|
25
|
+
print(f"[Fakex] Warning: Invalid locale '{locale}' ({exc}). Falling back to 'en_US'.")
|
|
26
|
+
self.locale = "en_US"
|
|
27
|
+
self.faker = Faker(locale="en_US")
|
|
28
|
+
self.rng = random.Random(seed)
|
|
29
|
+
if seed is not None:
|
|
30
|
+
self.faker.seed_instance(seed)
|
|
31
|
+
self.provider = LocaleRegistry.get_provider(self.locale, self.faker, rng=self.rng)
|
|
32
|
+
|
|
33
|
+
def _calculate_birthdate(self, min_age: int, max_age: int) -> tuple[date, int]:
|
|
34
|
+
"""Compute realistic birthdate and current age.
|
|
35
|
+
|
|
36
|
+
CRIT-03: Swaps inverted age_range so random.randint never receives (high, low),
|
|
37
|
+
and clamps values to a sane [0, 120] band.
|
|
38
|
+
"""
|
|
39
|
+
lower = min(120, max(0, min(min_age, max_age)))
|
|
40
|
+
upper = min(120, max(0, max(min_age, max_age)))
|
|
41
|
+
age = self.rng.randint(lower, upper)
|
|
42
|
+
days_in_year = 365
|
|
43
|
+
offset_days = self.rng.randint(0, 364)
|
|
44
|
+
birthdate = date.today() - timedelta(days=(age * days_in_year) + offset_days)
|
|
45
|
+
return birthdate, age
|
|
46
|
+
|
|
47
|
+
def generate_persona(
|
|
48
|
+
self,
|
|
49
|
+
gender: str = "random",
|
|
50
|
+
age_range: tuple[int, int] = (18, 65),
|
|
51
|
+
photo_source: str = "none",
|
|
52
|
+
download_dir: Path | str = "./downloads/photos",
|
|
53
|
+
crop_circle: bool = False,
|
|
54
|
+
) -> Persona:
|
|
55
|
+
"""Generate a single validated Persona instance."""
|
|
56
|
+
# MED-03: Accept None/empty gender gracefully — treat as "random"
|
|
57
|
+
resolved_gender = (gender or "random").lower().strip()
|
|
58
|
+
if resolved_gender not in ("male", "female"):
|
|
59
|
+
resolved_gender = self.rng.choice(["male", "female"])
|
|
60
|
+
|
|
61
|
+
first_name, last_name, full_name = self.provider.generate_name(resolved_gender)
|
|
62
|
+
birthdate, age = self._calculate_birthdate(age_range[0], age_range[1])
|
|
63
|
+
address = self.provider.generate_address()
|
|
64
|
+
contact = self.provider.generate_contact(first_name, last_name)
|
|
65
|
+
bio = self.provider.generate_bio()
|
|
66
|
+
|
|
67
|
+
persona_id = str(uuid.uuid4())
|
|
68
|
+
photo_details = None
|
|
69
|
+
|
|
70
|
+
if photo_source.lower() not in ("none", "", PhotoProviderEnum.NONE.value):
|
|
71
|
+
fetcher = PhotoFetcher(download_dir=download_dir)
|
|
72
|
+
photo_details = fetcher.fetch_photo_sync(
|
|
73
|
+
provider=photo_source,
|
|
74
|
+
gender=resolved_gender,
|
|
75
|
+
persona_id=persona_id[:8]
|
|
76
|
+
)
|
|
77
|
+
if crop_circle and photo_details and photo_details.local_path:
|
|
78
|
+
try:
|
|
79
|
+
from fakex.photos.cropper import crop_to_circle
|
|
80
|
+
photo_details.local_path = crop_to_circle(photo_details.local_path)
|
|
81
|
+
# Optional avatar conversion must not discard the downloaded original.
|
|
82
|
+
except Exception: # noqa: BLE001, S110
|
|
83
|
+
pass
|
|
84
|
+
|
|
85
|
+
return Persona(
|
|
86
|
+
id=persona_id,
|
|
87
|
+
first_name=first_name,
|
|
88
|
+
last_name=last_name,
|
|
89
|
+
full_name=full_name,
|
|
90
|
+
gender=resolved_gender.lower(),
|
|
91
|
+
birthdate=birthdate,
|
|
92
|
+
age=age,
|
|
93
|
+
address=address,
|
|
94
|
+
contact=contact,
|
|
95
|
+
bio=bio,
|
|
96
|
+
photo=photo_details
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
def stream_personas(
|
|
100
|
+
self,
|
|
101
|
+
count: int,
|
|
102
|
+
gender: str = "random",
|
|
103
|
+
age_range: tuple[int, int] = (18, 65),
|
|
104
|
+
photo_source: str = "none",
|
|
105
|
+
download_dir: Path | str = "./downloads/photos",
|
|
106
|
+
crop_circle: bool = False,
|
|
107
|
+
) -> Generator[Persona, None, None]:
|
|
108
|
+
"""Memory-efficient generator yielding personas one by one."""
|
|
109
|
+
for _ in range(count):
|
|
110
|
+
yield self.generate_persona(
|
|
111
|
+
gender=gender,
|
|
112
|
+
age_range=age_range,
|
|
113
|
+
photo_source=photo_source,
|
|
114
|
+
download_dir=download_dir,
|
|
115
|
+
crop_circle=crop_circle,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
def generate_batch(
|
|
119
|
+
self,
|
|
120
|
+
count: int,
|
|
121
|
+
gender: str = "random",
|
|
122
|
+
age_range: tuple[int, int] = (18, 65),
|
|
123
|
+
photo_source: str = "none",
|
|
124
|
+
download_dir: Path | str = "./downloads/photos",
|
|
125
|
+
crop_circle: bool = False,
|
|
126
|
+
) -> list[Persona]:
|
|
127
|
+
"""Generate a batch list of personas."""
|
|
128
|
+
return list(self.stream_personas(
|
|
129
|
+
count=count,
|
|
130
|
+
gender=gender,
|
|
131
|
+
age_range=age_range,
|
|
132
|
+
photo_source=photo_source,
|
|
133
|
+
download_dir=download_dir,
|
|
134
|
+
crop_circle=crop_circle,
|
|
135
|
+
))
|
|
136
|
+
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Exporters package for Fakex."""
|
|
2
|
+
|
|
3
|
+
from fakex.exporters.csv_exporter import export_csv
|
|
4
|
+
from fakex.exporters.json_exporter import export_json
|
|
5
|
+
from fakex.exporters.sqlite_exporter import export_sqlite
|
|
6
|
+
|
|
7
|
+
__all__ = ["export_csv", "export_json", "export_sqlite"]
|
|
8
|
+
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""CSV exporter for flattened persona data."""
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
from collections.abc import Sequence
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from fakex.models import Persona
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def export_csv(
|
|
11
|
+
personas: Persona | Sequence[Persona],
|
|
12
|
+
file_path: str | Path
|
|
13
|
+
) -> Path:
|
|
14
|
+
"""Export sequence or single persona to a flat CSV file."""
|
|
15
|
+
path = Path(file_path).resolve()
|
|
16
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
17
|
+
|
|
18
|
+
if isinstance(personas, Persona):
|
|
19
|
+
personas = [personas]
|
|
20
|
+
|
|
21
|
+
fieldnames = [
|
|
22
|
+
"id", "full_name", "first_name", "last_name", "gender",
|
|
23
|
+
"birthdate", "age", "email", "phone", "username",
|
|
24
|
+
"street", "city", "state_or_division", "postal_code", "country",
|
|
25
|
+
"full_address", "job_title", "company", "industry", "skills", "summary",
|
|
26
|
+
"photo_provider", "photo_url", "photo_local_path"
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
with open(path, "w", newline="", encoding="utf-8") as csvfile:
|
|
30
|
+
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
|
|
31
|
+
writer.writeheader()
|
|
32
|
+
|
|
33
|
+
for p in personas:
|
|
34
|
+
writer.writerow({
|
|
35
|
+
"id": p.id,
|
|
36
|
+
"full_name": p.full_name,
|
|
37
|
+
"first_name": p.first_name,
|
|
38
|
+
"last_name": p.last_name,
|
|
39
|
+
"gender": p.gender,
|
|
40
|
+
"birthdate": str(p.birthdate),
|
|
41
|
+
"age": p.age,
|
|
42
|
+
"email": p.contact.email,
|
|
43
|
+
"phone": p.contact.phone,
|
|
44
|
+
"username": p.contact.username,
|
|
45
|
+
"street": p.address.street,
|
|
46
|
+
"city": p.address.city,
|
|
47
|
+
"state_or_division": p.address.state_or_division,
|
|
48
|
+
"postal_code": p.address.postal_code,
|
|
49
|
+
"country": p.address.country,
|
|
50
|
+
"full_address": p.address.full_address,
|
|
51
|
+
"job_title": p.bio.job_title,
|
|
52
|
+
"company": p.bio.company,
|
|
53
|
+
"industry": p.bio.industry,
|
|
54
|
+
"skills": ", ".join(p.bio.skills),
|
|
55
|
+
"summary": p.bio.summary,
|
|
56
|
+
"photo_provider": p.photo.provider if p.photo else "",
|
|
57
|
+
"photo_url": p.photo.url if p.photo else "",
|
|
58
|
+
"photo_local_path": str(p.photo.local_path) if p.photo and p.photo.local_path else "",
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
return path
|
|
62
|
+
|