ethnidata 1.0.0__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.
ethnidata/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ """
2
+ EthniData - Ethnicity and Nationality Prediction from Names
3
+ Predict nationality, ethnicity, and demographics from names
4
+
5
+ Usage:
6
+ from ethnidata import EthniData
7
+
8
+ ed = EthniData()
9
+
10
+ # Predict nationality
11
+ result = ed.predict_nationality("Ahmet")
12
+ # {'name': 'ahmet', 'country': 'TUR', 'confidence': 0.85, 'top_countries': [...]}
13
+
14
+ # Predict ethnicity
15
+ result = ed.predict_ethnicity("Tanaka", name_type="last")
16
+ # {'name': 'tanaka', 'ethnicity': 'East Asian', 'country': 'JPN', ...}
17
+ """
18
+
19
+ __version__ = "1.0.0"
20
+ __author__ = "Tefik Yavuz Oz"
21
+ __license__ = "MIT"
22
+
23
+ from .predictor import EthniData
24
+
25
+ __all__ = ["EthniData"]
ethnidata/predictor.py ADDED
@@ -0,0 +1,277 @@
1
+ """
2
+ EthniData Predictor - Ana tahmin modülü
3
+ """
4
+
5
+ import sqlite3
6
+ from pathlib import Path
7
+ from typing import Dict, List, Optional, Literal
8
+ from unidecode import unidecode
9
+ import pycountry
10
+
11
+ class EthniData:
12
+ """Ethnicity and Nationality Data predictor"""
13
+
14
+ def __init__(self, db_path: Optional[str] = None):
15
+ """
16
+ Initialize EthniData predictor
17
+
18
+ Args:
19
+ db_path: Path to SQLite database. If None, uses default location.
20
+ """
21
+ if db_path is None:
22
+ db_path = Path(__file__).parent / "ethnidata.db"
23
+
24
+ self.db_path = Path(db_path)
25
+
26
+ if not self.db_path.exists():
27
+ raise FileNotFoundError(
28
+ f"Database not found: {self.db_path}\n"
29
+ f"Please run scripts/6_create_database.py first"
30
+ )
31
+
32
+ self.conn = sqlite3.connect(self.db_path)
33
+ self.conn.row_factory = sqlite3.Row
34
+
35
+ def __del__(self):
36
+ """Close database connection"""
37
+ if hasattr(self, 'conn'):
38
+ self.conn.close()
39
+
40
+ @staticmethod
41
+ def normalize_name(name: str) -> str:
42
+ """Normalize name (lowercase, remove accents)"""
43
+ return unidecode(name.strip().lower())
44
+
45
+ def predict_nationality(
46
+ self,
47
+ name: str,
48
+ name_type: Literal["first", "last"] = "first",
49
+ top_n: int = 5
50
+ ) -> Dict:
51
+ """
52
+ Predict nationality from name
53
+
54
+ Args:
55
+ name: First or last name
56
+ name_type: "first" or "last"
57
+ top_n: Number of top predictions to return
58
+
59
+ Returns:
60
+ {
61
+ 'name': normalized name,
62
+ 'country': top country code (ISO 3166-1 alpha-3),
63
+ 'confidence': confidence score (0-1),
64
+ 'top_countries': [{country, probability, frequency}, ...]
65
+ }
66
+ """
67
+
68
+ normalized = self.normalize_name(name)
69
+
70
+ table = "first_names" if name_type == "first" else "last_names"
71
+
72
+ # Query database
73
+ query = f"""
74
+ SELECT country_code, frequency
75
+ FROM {table}
76
+ WHERE name = ?
77
+ ORDER BY frequency DESC
78
+ LIMIT ?
79
+ """
80
+
81
+ cursor = self.conn.cursor()
82
+ cursor.execute(query, (normalized, top_n))
83
+
84
+ results = cursor.fetchall()
85
+
86
+ if not results:
87
+ return {
88
+ 'name': normalized,
89
+ 'country': None,
90
+ 'confidence': 0.0,
91
+ 'top_countries': []
92
+ }
93
+
94
+ # Calculate probabilities
95
+ total_frequency = sum(row['frequency'] for row in results)
96
+
97
+ top_countries = []
98
+ for row in results:
99
+ prob = row['frequency'] / total_frequency
100
+
101
+ # Country name lookup
102
+ try:
103
+ country = pycountry.countries.get(alpha_3=row['country_code'])
104
+ country_name = country.name if country else row['country_code']
105
+ except:
106
+ country_name = row['country_code']
107
+
108
+ top_countries.append({
109
+ 'country': row['country_code'],
110
+ 'country_name': country_name,
111
+ 'probability': round(prob, 4),
112
+ 'frequency': row['frequency']
113
+ })
114
+
115
+ # Top prediction
116
+ top = top_countries[0]
117
+
118
+ return {
119
+ 'name': normalized,
120
+ 'country': top['country'],
121
+ 'country_name': top['country_name'],
122
+ 'confidence': top['probability'],
123
+ 'top_countries': top_countries
124
+ }
125
+
126
+ def predict_ethnicity(
127
+ self,
128
+ name: str,
129
+ name_type: Literal["first", "last"] = "first"
130
+ ) -> Dict:
131
+ """
132
+ Predict ethnicity from name
133
+
134
+ Args:
135
+ name: First or last name
136
+ name_type: "first" or "last"
137
+
138
+ Returns:
139
+ {
140
+ 'name': normalized name,
141
+ 'ethnicity': predicted ethnicity,
142
+ 'country': most likely country,
143
+ 'confidence': confidence score
144
+ }
145
+ """
146
+
147
+ normalized = self.normalize_name(name)
148
+
149
+ table = "first_names" if name_type == "first" else "last_names"
150
+
151
+ # Query with ethnicity
152
+ query = f"""
153
+ SELECT country_code, ethnicity, frequency
154
+ FROM {table}
155
+ WHERE name = ? AND ethnicity IS NOT NULL
156
+ ORDER BY frequency DESC
157
+ LIMIT 1
158
+ """
159
+
160
+ cursor = self.conn.cursor()
161
+ cursor.execute(query, (normalized,))
162
+
163
+ result = cursor.fetchone()
164
+
165
+ if result:
166
+ # Country name
167
+ try:
168
+ country = pycountry.countries.get(alpha_3=result['country_code'])
169
+ country_name = country.name if country else result['country_code']
170
+ except:
171
+ country_name = result['country_code']
172
+
173
+ return {
174
+ 'name': normalized,
175
+ 'ethnicity': result['ethnicity'],
176
+ 'country': result['country_code'],
177
+ 'country_name': country_name,
178
+ 'frequency': result['frequency']
179
+ }
180
+
181
+ # Fallback to nationality prediction
182
+ nationality = self.predict_nationality(name, name_type, top_n=1)
183
+
184
+ return {
185
+ 'name': normalized,
186
+ 'ethnicity': None,
187
+ 'country': nationality['country'],
188
+ 'country_name': nationality.get('country_name'),
189
+ 'confidence': nationality['confidence']
190
+ }
191
+
192
+ def predict_full_name(
193
+ self,
194
+ first_name: str,
195
+ last_name: str,
196
+ top_n: int = 5
197
+ ) -> Dict:
198
+ """
199
+ Predict nationality from full name (first + last)
200
+
201
+ Combines predictions from both first and last names
202
+
203
+ Args:
204
+ first_name: First name
205
+ last_name: Last name
206
+ top_n: Number of top predictions
207
+
208
+ Returns:
209
+ Combined prediction with country probabilities
210
+ """
211
+
212
+ first_pred = self.predict_nationality(first_name, "first", top_n=top_n)
213
+ last_pred = self.predict_nationality(last_name, "last", top_n=top_n)
214
+
215
+ # Combine probabilities
216
+ combined_scores = {}
217
+
218
+ for item in first_pred['top_countries']:
219
+ combined_scores[item['country']] = item['probability'] * 0.4
220
+
221
+ for item in last_pred['top_countries']:
222
+ if item['country'] in combined_scores:
223
+ combined_scores[item['country']] += item['probability'] * 0.6
224
+ else:
225
+ combined_scores[item['country']] = item['probability'] * 0.6
226
+
227
+ # Sort by combined score
228
+ sorted_countries = sorted(
229
+ combined_scores.items(),
230
+ key=lambda x: x[1],
231
+ reverse=True
232
+ )[:top_n]
233
+
234
+ # Format results
235
+ top_countries = []
236
+ for country_code, score in sorted_countries:
237
+ try:
238
+ country = pycountry.countries.get(alpha_3=country_code)
239
+ country_name = country.name if country else country_code
240
+ except:
241
+ country_name = country_code
242
+
243
+ top_countries.append({
244
+ 'country': country_code,
245
+ 'country_name': country_name,
246
+ 'probability': round(score, 4)
247
+ })
248
+
249
+ return {
250
+ 'first_name': self.normalize_name(first_name),
251
+ 'last_name': self.normalize_name(last_name),
252
+ 'country': top_countries[0]['country'] if top_countries else None,
253
+ 'country_name': top_countries[0]['country_name'] if top_countries else None,
254
+ 'confidence': top_countries[0]['probability'] if top_countries else 0.0,
255
+ 'top_countries': top_countries
256
+ }
257
+
258
+ def get_stats(self) -> Dict:
259
+ """Get database statistics"""
260
+
261
+ cursor = self.conn.cursor()
262
+
263
+ stats = {}
264
+
265
+ cursor.execute("SELECT COUNT(*) as count FROM first_names")
266
+ stats['total_first_names'] = cursor.fetchone()['count']
267
+
268
+ cursor.execute("SELECT COUNT(*) as count FROM last_names")
269
+ stats['total_last_names'] = cursor.fetchone()['count']
270
+
271
+ cursor.execute("SELECT COUNT(DISTINCT country_code) as count FROM first_names")
272
+ stats['countries_first'] = cursor.fetchone()['count']
273
+
274
+ cursor.execute("SELECT COUNT(DISTINCT country_code) as count FROM last_names")
275
+ stats['countries_last'] = cursor.fetchone()['count']
276
+
277
+ return stats
@@ -0,0 +1,257 @@
1
+ Metadata-Version: 2.4
2
+ Name: ethnidata
3
+ Version: 1.0.0
4
+ Summary: Predict nationality, ethnicity, and demographics from names using a comprehensive global database
5
+ Author-email: Tefik Yavuz Oz <teyfikoz@example.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/teyfikoz/ethnidata
8
+ Project-URL: Documentation, https://github.com/teyfikoz/ethnidata#readme
9
+ Project-URL: Repository, https://github.com/teyfikoz/ethnidata.git
10
+ Project-URL: Issues, https://github.com/teyfikoz/ethnidata/issues
11
+ Keywords: names,nationality,ethnicity,demographics,prediction,NLP
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Requires-Python: >=3.8
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: pycountry>=22.3.5
26
+ Requires-Dist: unidecode>=1.3.6
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
29
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
30
+ Provides-Extra: build
31
+ Requires-Dist: requests>=2.31.0; extra == "build"
32
+ Requires-Dist: pandas>=2.0.0; extra == "build"
33
+ Requires-Dist: numpy>=1.24.0; extra == "build"
34
+ Requires-Dist: beautifulsoup4>=4.12.0; extra == "build"
35
+ Requires-Dist: lxml>=4.9.0; extra == "build"
36
+ Requires-Dist: tqdm>=4.65.0; extra == "build"
37
+ Requires-Dist: wikipedia-api>=0.6.0; extra == "build"
38
+ Requires-Dist: sqlalchemy>=2.0.0; extra == "build"
39
+ Dynamic: license-file
40
+
41
+ # EthniData - Ethnicity and Nationality Prediction
42
+
43
+ [![Python](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
44
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
45
+ [![PyPI version](https://badge.fury.io/py/ethnidata.svg)](https://badge.fury.io/py/ethnidata)
46
+
47
+ Predict **nationality**, **ethnicity**, and **demographics** from names using a comprehensive global database built from multiple authoritative sources.
48
+
49
+ ## 🌟 Features
50
+
51
+ - **190+ Countries** - Comprehensive coverage from Wikipedia/Wikidata
52
+ - **106 Countries** - Enhanced with names-dataset
53
+ - **120 Years** of Olympic athlete names
54
+ - **Multiple Sources** - Phone directories, census data, public records
55
+ - **Fast Predictions** - SQLite-based for instant lookups
56
+ - **Normalized Data** - Unicode-aware, case-insensitive matching
57
+ - **Ethnicity Support** - Where available in source data
58
+ - **Simple API** - Easy to use Python interface
59
+
60
+ ## 📊 Data Sources
61
+
62
+ 1. **Wikipedia/Wikidata** - 190+ countries, biographical data with ethnicity
63
+ 2. **names-dataset** - 106 countries, curated name lists
64
+ 3. **Olympics Dataset** - 120 years of athlete names (271,116 records)
65
+ 4. **Phone Directories** - Public domain name lists from multiple countries
66
+ 5. **Census Data** - US Census and other government open data
67
+
68
+ ## 🚀 Installation
69
+
70
+ ```bash
71
+ pip install ethnidata
72
+ ```
73
+
74
+ ## 📖 Usage
75
+
76
+ ### Basic Usage
77
+
78
+ ```python
79
+ from ethnidata import EthniData
80
+
81
+ # Initialize
82
+ ed = EthniData()
83
+
84
+ # Predict nationality from first name
85
+ result = ed.predict_nationality("Ahmet", name_type="first")
86
+ print(result)
87
+ # {
88
+ # 'name': 'ahmet',
89
+ # 'country': 'TUR',
90
+ # 'country_name': 'Turkey',
91
+ # 'confidence': 0.89,
92
+ # 'top_countries': [
93
+ # {'country': 'TUR', 'country_name': 'Turkey', 'probability': 0.89},
94
+ # {'country': 'DEU', 'country_name': 'Germany', 'probability': 0.07},
95
+ # ...
96
+ # ]
97
+ # }
98
+
99
+ # Predict from last name
100
+ result = ed.predict_nationality("Tanaka", name_type="last")
101
+ print(result['country']) # 'JPN'
102
+
103
+ # Predict from full name (combines both)
104
+ result = ed.predict_full_name("Wei", "Chen")
105
+ print(result['country']) # 'CHN'
106
+
107
+ # Predict ethnicity (when available)
108
+ result = ed.predict_ethnicity("Muhammad", name_type="first")
109
+ print(result)
110
+ # {
111
+ # 'name': 'muhammad',
112
+ # 'ethnicity': 'Arab',
113
+ # 'country': 'SAU',
114
+ # 'country_name': 'Saudi Arabia'
115
+ # }
116
+ ```
117
+
118
+ ### Advanced Usage
119
+
120
+ ```python
121
+ # Get top 10 predictions
122
+ result = ed.predict_nationality("Maria", name_type="first", top_n=10)
123
+
124
+ for country in result['top_countries']:
125
+ print(f"{country['country_name']}: {country['probability']:.2%}")
126
+ # Spain: 35.4%
127
+ # Italy: 28.2%
128
+ # Portugal: 15.1%
129
+ # ...
130
+
131
+ # Database statistics
132
+ stats = ed.get_stats()
133
+ print(stats)
134
+ # {
135
+ # 'total_first_names': 123456,
136
+ # 'total_last_names': 234567,
137
+ # 'countries_first': 195,
138
+ # 'countries_last': 198
139
+ # }
140
+ ```
141
+
142
+ ## 🏗️ Project Structure
143
+
144
+ ```
145
+ ethnidata/
146
+ ├── ethnidata/ # Main package
147
+ │ ├── __init__.py
148
+ │ ├── predictor.py # Core prediction logic
149
+ │ └── ethnidata.db # SQLite database
150
+ ├── scripts/ # Data collection scripts
151
+ │ ├── 1_fetch_names_dataset.py
152
+ │ ├── 2_fetch_wikipedia.py
153
+ │ ├── 3_fetch_olympics.py
154
+ │ ├── 4_fetch_phone_directories.py
155
+ │ ├── 5_merge_all_data.py
156
+ │ └── 6_create_database.py
157
+ ├── tests/ # Unit tests
158
+ ├── examples/ # Example scripts
159
+ ├── docs/ # Documentation
160
+ ├── setup.py
161
+ ├── pyproject.toml
162
+ └── README.md
163
+ ```
164
+
165
+ ## 🔬 Accuracy & Methodology
166
+
167
+ ### How it works
168
+
169
+ 1. **Name Normalization**: Names are lowercased and Unicode-normalized (e.g., "José" → "jose")
170
+ 2. **Database Lookup**: Queries SQLite database for matching names
171
+ 3. **Frequency-Based Scoring**: Countries are ranked by how often the name appears
172
+ 4. **Probability Calculation**: Frequencies are converted to probabilities
173
+ 5. **Full Name Combination**: First name (40%) + last name (60%) weights
174
+
175
+ ### Limitations
176
+
177
+ - **Bias**: Database reflects historical Olympic participation, Wikipedia coverage
178
+ - **Missing Names**: Rare or new names may not be in database
179
+ - **Ethnicity**: Only available where source data included it
180
+ - **Migration**: Doesn't account for diaspora or modern migration patterns
181
+ - **Multiple Origins**: Common names (e.g., "Ali", "Maria") exist in many cultures
182
+
183
+ ## 🛠️ Development
184
+
185
+ ### Build Database from Scratch
186
+
187
+ ```bash
188
+ git clone https://github.com/teyfikoz/ethnidata.git
189
+ cd ethnidata
190
+
191
+ # Install dependencies
192
+ pip install -r requirements.txt
193
+
194
+ # Fetch all data (takes 10-30 minutes)
195
+ cd scripts
196
+ python 1_fetch_names_dataset.py
197
+ python 2_fetch_wikipedia.py
198
+ python 3_fetch_olympics.py
199
+ python 4_fetch_phone_directories.py
200
+ python 5_merge_all_data.py
201
+ python 6_create_database.py
202
+ ```
203
+
204
+ ### Run Tests
205
+
206
+ ```bash
207
+ pip install -e ".[dev]"
208
+ pytest tests/ -v
209
+ ```
210
+
211
+ ## 📜 License
212
+
213
+ MIT License - see [LICENSE](LICENSE) file for details
214
+
215
+ ## 🤝 Contributing
216
+
217
+ Contributions welcome! Please:
218
+
219
+ 1. Fork the repository
220
+ 2. Create a feature branch
221
+ 3. Commit your changes
222
+ 4. Push to the branch
223
+ 5. Open a Pull Request
224
+
225
+ ## 📚 Citations
226
+
227
+ If you use this database in research, please cite:
228
+
229
+ ```bibtex
230
+ @software{ethnidata_2024,
231
+ title = {EthniData: Ethnicity and Nationality Prediction from Names},
232
+ author = {Oz, Tefik Yavuz},
233
+ year = {2024},
234
+ url = {https://github.com/teyfikoz/ethnidata}
235
+ }
236
+ ```
237
+
238
+ ### Data Source Citations
239
+
240
+ - **Olympics Data**: Randi Griffin (2018). 120 years of Olympic history. [Kaggle](https://www.kaggle.com/datasets/heesoo37/120-years-of-olympic-history-athletes-and-results)
241
+ - **names-dataset**: Philippe Remy (2021). [name-dataset](https://github.com/philipperemy/name-dataset)
242
+ - **Wikidata**: Wikimedia Foundation. [Wikidata](https://www.wikidata.org)
243
+
244
+ ## 🔗 Related Projects
245
+
246
+ - [ethnicolr](https://github.com/appeler/ethnicolr) - Ethnicity prediction using LSTM
247
+ - [name-dataset](https://github.com/philipperemy/name-dataset) - Name database (106 countries)
248
+ - [gender-guesser](https://github.com/lead-ratings/gender-guesser) - Gender prediction
249
+
250
+ ## 📧 Contact
251
+
252
+ - GitHub Issues: [Report bugs or request features](https://github.com/teyfikoz/ethnidata/issues)
253
+ - GitHub: [@teyfikoz](https://github.com/teyfikoz)
254
+
255
+ ---
256
+
257
+ **Built with ❤️ using open data**
@@ -0,0 +1,7 @@
1
+ ethnidata/__init__.py,sha256=IKcroHkdOagBd9oaem6VhqjdfDn28iQPiFc9tepI9OE,671
2
+ ethnidata/predictor.py,sha256=dGmfYWTO2BRYxQUzzE7foZMEEDaOd6VWPZk4ib5Gp9E,8696
3
+ ethnidata-1.0.0.dist-info/licenses/LICENSE,sha256=p5pRNvuSoG_JxH4Xy11FK2iXc3hyAnzOKUx9gBltulk,1095
4
+ ethnidata-1.0.0.dist-info/METADATA,sha256=FTPxHrFXh2F452Gg5mJMLWFqi0hHLVCTs-Kr2uQ_B0M,8132
5
+ ethnidata-1.0.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
6
+ ethnidata-1.0.0.dist-info/top_level.txt,sha256=V5Cuyv_Ib3mDSp2KL8MocXzLyp3o3r2FG01rFA7Iatk,10
7
+ ethnidata-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 NBD Database Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ ethnidata