Code Monkey home page Code Monkey logo

python-codicefiscale's Introduction

python-codicefiscale

python-codicefiscale is a library for encode/decode Italian fiscal code - codifica/decodifica del Codice Fiscale.

Codice Fiscale

Features

  • NEW Auto-updated data (once a week) directly from ANPR data-source.
  • NEW Command Line Interface available.
  • Transliteration for name/surname
  • Multiple birthdate formats (date/string) (you can see all the supported string formats here)
  • Automatic birthplace city/foreign-country code detection from name
  • Omocodia support

Installation

pip install python-codicefiscale

Usage

Python

Import

from codicefiscale import codicefiscale

Encode

codicefiscale.encode(
    lastname="Caccamo",
    firstname="Fabio",
    gender="M",
    birthdate="03/04/1985",
    birthplace="Torino",
)

# "CCCFBA85D03L219P"

Decode

codicefiscale.decode("CCCFBA85D03L219P")

# {
#     "code": "CCCFBA85D03L219P",
#     "gender": "M",
#     "birthdate": datetime.datetime(1985, 4, 3, 0, 0),
#     "birthplace": {
#         "name": "TORINO"
#         "province": "TO",
#         "code": "L219",
#     },
#     "omocodes": [
#         "CCCFBA85D03L219P",
#         "CCCFBA85D03L21VE",
#         "CCCFBA85D03L2MVP",
#         "CCCFBA85D03LNMVE",
#         "CCCFBA85D0PLNMVA",
#         "CCCFBA85DLPLNMVL",
#         "CCCFBA8RDLPLNMVX",
#         "CCCFBAURDLPLNMVU",
#     ],
#     "raw": {
#         "code": "CCCFBA85D03L219P",
#         "lastname": "CCC",
#         "firstname": "FBA",
#         "birthdate": "85D03",
#         "birthdate_year": "85"
#         "birthdate_month": "D",
#         "birthdate_day": "03",
#         "birthplace": "L219",
#         "cin": "P",
#     },
# }

Check

codicefiscale.is_valid("CCCFBA85D03L219P")

# True
codicefiscale.is_omocode("CCCFBA85D03L219P")

# False

Command Line

This library can be used also as a CLI tool, for more info run:

python -m codicefiscale --help

Encode (CLI)

python -m codicefiscale encode --firstname Fabio --lastname Caccamo --gender M --birthdate 03/04/1985 --birthplace Torino

Decode (CLI)

python -m codicefiscale decode CCCFBA85D03L219P

Testing

# clone repository
git clone https://github.com/fabiocaccamo/python-codicefiscale.git && cd python-codicefiscale

# create virtualenv and activate it
python -m venv venv && . venv/bin/activate

# upgrade pip
python -m pip install --upgrade pip

# install requirements
pip install -r requirements.txt -r requirements-test.txt

# install pre-commit to run formatters and linters
pre-commit install --install-hooks

# run tests using tox
tox

# or run tests using unittest
python -m unittest tests.tests

License

Released under MIT License.


Supporting

See also

  • python-benedict - dict subclass with keylist/keypath support, I/O shortcuts (base64, csv, json, pickle, plist, query-string, toml, xml, yaml) and many utilities. 📘

  • python-fontbro - friendly font operations. 🧢

  • python-fsutil - file-system utilities for lazy devs. 🧟‍♂️

python-codicefiscale's People

Contributors

danisana avatar dbaty avatar dependabot[bot] avatar fabiocaccamo avatar github-actions[bot] avatar guglielmo avatar pre-commit-ci[bot] avatar syberworld avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

python-codicefiscale's Issues

`codicefiscale.is_valid` with invalid birthplace codes throw TypeException exception

Python version
3.9.13

Package version
0.5.0

Current behavior (bug description)
When doing the following,

x = "FRTMXM74L15D354A"
codicefiscale.is_valid(x)

the method throws a TypeError with the following stacktrace

Traceback (most recent call last):
File "", line 1, in
File "/opt/conda/lib/python3.9/site-packages/codicefiscale/codicefiscale.py", line 477, in is_valid
decode(code)
File "/opt/conda/lib/python3.9/site-packages/codicefiscale/codicefiscale.py", line 422, in decode
for birthplace_option in birthplaces_options:
TypeError: 'NoneType' object is not iterable

Expected behavior
False

Decode ritorna GIRGENTI (soppresso) invece di AGRIGENTO

Python version
3.8

Package version
0.3.7

Current behavior (bug description)
print(codicefiscale.decode('LNNFNC80A01A089K')) restituisce:
{'code': 'LNNFNC80A01A089K', 'omocodes': ['LNNFNC80A01A089K', 'LNNFNC80A01A08VZ', 'LNNFNC80A01A0UVL', 'LNNFNC80A01ALUVO', 'LNNFNC80A0MALUVG', 'LNNFNC80ALMALUVR', 'LNNFNC8LALMALUVC', 'LNNFNCULALMALUVZ'], 'sex': 'M', 'birthdate': datetime.datetime(1980, 1, 1, 0, 0), 'birthplace': {'code': 'A089', 'province': 'AG', 'name': 'GIRGENTI (soppresso)'}, 'raw': {'code': 'LNNFNC80A01A089K', 'surname': 'LNN', 'name': 'FNC', 'birthdate': '80A01', 'birthdate_year': '80', 'birthdate_month': 'A', 'birthdate_day': '01', 'birthplace': 'A089', 'cin': 'K'}}

Expected behavior
Mi aspetto come birthplace di trovare AGRIGENTO o al limite una lista con entrambi, non solo il comune soppresso.

Il CF LNNFNC80A01A089K è inventato ma il bug l'ho riscontrato con un CF vero.

Issue with Incorrect Validation of Valid 'Codice Fiscale'

Python version
3.11.2

Package version
0.9.1

Current behavior (bug description)
I've encountered an issue with the library's validation function, where it incorrectly marks a certain Italian "codice fiscale" as invalid. The "codice fiscale" in question is validated correctly on the official website of the Italian "Agenzia delle Entrate."

Expected behavior
The library should validate this pattern as it aligns with the format deemed valid by the "Agenzia delle Entrate".

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • We receive the funding once the issue is completed & confirmed by you.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Add check commad in the cli

python -m codicefiscale check CCCFBA85D03L219P

returns true/false

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • We receive the funding once the issue is completed & confirmed by you.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Date Formats

The link in the read me to:
Multiple birthdate formats (date/string) (you can see all the supported string formats here)

Does not work... hence, no idea what or how to use the date formats.

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • We receive the funding once the issue is completed & confirmed by you.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

💡 Add this project to awesome-italia-opensource

I founded Italia Open-source, a community that aims to share and grow the Italian open-source world, but more generally to highlight Italian tech excellence.

Our website italiaopensource.com is based on open data that reside on the awesome-italia-opensource repository, you can add your own open-source project, community tech(s), and much more. All through a simple pull request, you can add your data.

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • We receive the funding once the issue is completed & confirmed by you.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Gcode

Python version
?

Package version
?

Current behavior (bug description)
?

Expected behavior
?

[INFO] FOSS Explorer

Ciao!

La tua repository è stata selezionata dalla nostra redazione per il format "FOSS Explorer" di Schrodinger Hat, una rubrica del nostro talk show riguardo il software development e il mondo open source italiano, e verrà mostrata nella puntata di Martedì 26 Maggio in diretta sul canale Twitch e YouTube alle ore 13.00.

Il tuo lavoro ci è piaciuto molto e speriamo che questo possa aiutare a fornire visibilità al tuo lavoro ;)
Se per te va bene, la includeremo nella nostra top15 bisettimanale!

A presto!

Dictionary on municipality name and avoid name mangling

Hi Fabio! First of all, thanks for this library.

I'm using it to validate some user input in a project, and I'd like to extend your library with a dictionary ordered on the municipality name, something like:

{'ABANO TERME': {'code': 'A001', 'name': 'ABANO TERME', 'province': 'PD'},
 'ABBADIA CERRETO': {'code': 'A004', 'name': 'ABBADIA CERRETO', 'province': 'LO'},
 ...
}

I'd like to retrieve the Belfiore code and the province given a municipality name, but since there's only a list of municipalities in data.__MUNICIPALITIES, each search costs O(n).

Moreover, since codicefiscale.__DATA, data.__MUNICIPALITIES and data.__COUNTRIES are defined with the double underscore, in order to use them in my project, I had to use getattr on the modules due to name mangling.
Wouldn't a single underscore "suffice"?

So I'd like to propose two PRs: the first creating a new __MUNICIPALITIES dictionary with municipality names as keys (I know that inside __DATA there is already, but the names are slugified) and the second adding some "aliases" with a single leading underscore pointing to __DATA, __MUNICIPALITIES and __COUNTRIES (in order not to break existing setups).

Thanks!

Number of omocodes

According to Wikipedia, the total number of "omocodes" that can be derived from a fiscal code is 128, as it includes all possible combinations of number -> letter substitutions (that is 27).

This library only considers (and returns) 8 of them, as it only takes into account one substitution for each digit of the code.

Birth year

Python version
3.8.6

Package version
0.3.7

Current behavior (bug description)
Tax codes with "21" as birth year are decoded as 2021

Expected behavior
Tax codes with "21" as birth year decoded correctly as 1921 or 2021

Amend Reggio di Calabria and Reggio nell'Emilia

Very good job, thanks.
You should consider to replace (or at least add) "Reggio di Calabria" with "Reggio Calabria" and "Reggio nell'Emilia" with "Reggio Emilia" as these are actually the more common names.
Thanks
Nico

Unable to encode and decode fiscal codes when year of birth (excluding century) < 10 (eg. 2004)

Python version
3.9

Current behavior (bug description)
When calling both the .encode and .decode function with any birthplace it raises a ValueError:
Traceback (most recent call last):
File "/Users/davideramondetti/..../handler.py", line 19, in
cod1 = codicefiscale.decode(
File "/Users/davideramondetti/.../venv/lib/python3.9/site-packages/codicefiscale/codicefiscale.py", line 485, in decode
raise ValueError(f"[codicefiscale] wrong birthplace code: {birthplace_code!r}")
ValueError: [codicefiscale] wrong birthplace code: 'L219'

Expected behavior
It is expected for the .decode to return the extracted data, and for the Encode to output the fiscal code.

Code Z118 (Jugoslavia) not recognised, in general file countries.json don't manage deleted countries

Python version
3.10

Package version
I'm installing main branch with pip

Current behavior (bug description)
A Fiscal Code with birthplace code set as Z118 (code for ex-country Jugoslavia) are marked as invalid when using codicefiscale.is_valid() function. When I open up the countries.json file I cannot find that code inside but I notice that all codes have as date_created value "01/01/1900 00:00:00" and date_deleted ""
I don't know if this is the desired behaviour, but I think there is no management of deleted foreign country.
In my code I've added an exception for that code (It's only one person in a database) but I want to inform about this behaviour

Expected behavior
CF with code Z118 should be recognised as a Foreign Person born in a deleted country

Wrong birthplace code error (missing date-range in the data-source).

Python version
3.9

Package version
0.6.1

Current behavior (bug description)
Hi! I got this error when decoding a valid codicefiscale value.

Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python3.9/site-packages/codicefiscale/codicefiscale.py", line 440, in decode
raise ValueError(f"[codicefiscale] wrong birthplace code: '{birthplace_code}'")
ValueError: [codicefiscale] wrong birthplace code: 'G133'

I think some entry is missing in the municipalities.json file, in particular for the range from 1928-11-27 to 1948-05-07.

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • We receive the funding once the issue is completed & confirmed by you.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Error on date before 1969

Inverse code before 1969 return birthdate in after 2000.
For example RSSMRA68A01H501Y (01.01.1968) return birthdate datetime.datetime(2068, 1, 1, 0, 0)

Allow access to data files when running in a frozen environment (eg. executable).

Discussed in #151

Originally posted by goldelay January 30, 2024
Ciao Fabio, per poter accedere alle informazioni data/municipalities.json etc... su una build eseguibile effettuata con pyinstaller ho dovuto modificare il codice di data.py applicando questa fix:

from __future__ import annotations

from datetime import datetime
from typing import Any

import fsutil

import sys, os


def get_temp_dir():
    if getattr(sys, 'frozen', False):
        # Se l'applicazione è un eseguibile standalone
        return os.path.dirname(sys.executable)
    else:
        # Se l'applicazione è eseguita come script Python
        return os.path.dirname(os.path.abspath(__file__))


def get_data(filename: str) -> Any:
    return fsutil.read_file_json(fsutil.join_path(get_temp_dir(), f"data/{filename}"))
    #return fsutil.read_file_json(fsutil.join_path(__file__, f"data/{filename}"))

la function get_temp_dir() serve ovviamente a dirottare le chiamate per caricare i file dalla cartella del componente di python alla root dell'esegiubile nel momento in cui è un eseguibile.

In questo modo copiando la cartella .\data*.json contenuta dentro al tuo componente dentro la root dell'applicazione EXE permette di funzionare riuscendo così ad elaborare i dati per generare e verificare il codice fiscale al di fuori quindi del contesto python/componente.

Spero di esser stato d'aiuto

Saluti
Umberto Neri

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • We receive the funding once the issue is completed & confirmed by you.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Get all cities/nations names

Crate a method or a property which returns all cities and nations names, in order to have all accepted options for a birth city field

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • We receive the funding once the issue is completed & confirmed by you.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Wrong validity check after 0.5.0 version

Python version
3.10

Package version
0.8.1

Current behavior (bug description)
Some valid fiscal codes validated in versions since 0.5.0 are not validated in later versions.
I cant' provide a real fiscal code to test (for privacy reasons) but i can provide some other details for the debug:

Birth place: MONTECHIARO D’ACQUI
Province: AL
Birth date: 04/03/1940
Sex: M

Birth place: PRIERO
Province: CN
Birth date: 18/01/1941
Sex: F

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • We receive the funding once the issue is completed & confirmed by you.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Unactive municipalities cannot be retrieved

Python version
3.9.9

Package version
0.4.0

Current behavior (bug description)
Decoding does not work for inactive municipalities, since only active ones are considered in

for municipality in municipalities:
   if not municipality["active"]:
      continue

Expected behavior
inactive municipalities data should be considered.
When multiple entries are available, take the one where birthday falls within date_created and date_deleted

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.