|
| 1 | +import io |
| 2 | +import json |
| 3 | +from explorer.ee.db_connections.mime import is_csv, is_json, is_sqlite, is_json_list |
| 4 | + |
| 5 | + |
| 6 | +MAX_TYPING_SAMPLE_SIZE = 5000 |
| 7 | +SHORTEST_PLAUSIBLE_DATE_STRING = 5 |
| 8 | + |
| 9 | + |
| 10 | +def get_parser(file): |
| 11 | + if is_csv(file): |
| 12 | + return csv_to_typed_df |
| 13 | + if is_json_list(file): |
| 14 | + return json_list_to_typed_df |
| 15 | + if is_json(file): |
| 16 | + return json_to_typed_df |
| 17 | + if is_sqlite(file): |
| 18 | + return None |
| 19 | + raise ValueError(f"File {file.content_type} not supported.") |
| 20 | + |
| 21 | + |
| 22 | +def csv_to_typed_df(csv_bytes, delimiter=",", has_headers=True): |
| 23 | + import pandas as pd |
| 24 | + csv_file = io.BytesIO(csv_bytes) |
| 25 | + df = pd.read_csv(csv_file, sep=delimiter, header=0 if has_headers else None) |
| 26 | + return df_to_typed_df(df) |
| 27 | + |
| 28 | + |
| 29 | +def json_list_to_typed_df(json_bytes): |
| 30 | + import pandas as pd |
| 31 | + data = [] |
| 32 | + for line in io.BytesIO(json_bytes).readlines(): |
| 33 | + data.append(json.loads(line.decode("utf-8"))) |
| 34 | + |
| 35 | + df = pd.json_normalize(data) |
| 36 | + return df_to_typed_df(df) |
| 37 | + |
| 38 | + |
| 39 | +def json_to_typed_df(json_bytes): |
| 40 | + import pandas as pd |
| 41 | + json_file = io.BytesIO(json_bytes) |
| 42 | + json_content = json.load(json_file) |
| 43 | + df = pd.json_normalize(json_content) |
| 44 | + return df_to_typed_df(df) |
| 45 | + |
| 46 | + |
| 47 | +def atof_custom(value): |
| 48 | + # Remove any thousands separators and convert the decimal point |
| 49 | + if "," in value and "." in value: |
| 50 | + if value.index(",") < value.index("."): |
| 51 | + # 0,000.00 format |
| 52 | + value = value.replace(",", "") |
| 53 | + else: |
| 54 | + # 0.000,00 format |
| 55 | + value = value.replace(".", "").replace(",", ".") |
| 56 | + elif "," in value: |
| 57 | + # No decimal point, only thousands separator |
| 58 | + value = value.replace(",", "") |
| 59 | + return float(value) |
| 60 | + |
| 61 | + |
| 62 | + |
| 63 | +def df_to_typed_df(df): # noqa |
| 64 | + import pandas as pd |
| 65 | + from dateutil import parser |
| 66 | + try: |
| 67 | + |
| 68 | + for column in df.columns: |
| 69 | + |
| 70 | + # If we somehow have an array within a field (e.g. from a json object) then convert it to a string |
| 71 | + df[column] = df[column].apply(lambda x: str(x) if isinstance(x, list) else x) |
| 72 | + |
| 73 | + values = df[column].dropna().unique() |
| 74 | + if len(values) > MAX_TYPING_SAMPLE_SIZE: |
| 75 | + values = pd.Series(values).sample(MAX_TYPING_SAMPLE_SIZE, random_state=42).to_numpy() |
| 76 | + |
| 77 | + is_date = False |
| 78 | + is_integer = True |
| 79 | + is_float = True |
| 80 | + |
| 81 | + for value in values: |
| 82 | + try: |
| 83 | + float_val = atof_custom(str(value)) |
| 84 | + if float_val == int(float_val): |
| 85 | + continue # This is effectively an integer |
| 86 | + else: |
| 87 | + is_integer = False |
| 88 | + except ValueError: |
| 89 | + is_integer = False |
| 90 | + is_float = False |
| 91 | + break |
| 92 | + |
| 93 | + if is_integer: |
| 94 | + is_float = False |
| 95 | + |
| 96 | + if not is_integer and not is_float: |
| 97 | + is_date = True |
| 98 | + |
| 99 | + # The dateutil parser is very aggressive and will interpret many short strings as dates. |
| 100 | + # For example "12a" will be interpreted as 12:00 AM on the current date. |
| 101 | + # That is not the behavior anyone wants. The shortest plausible date string is e.g. 1-1-23 |
| 102 | + try_parse = [v for v in values if len(str(v)) > SHORTEST_PLAUSIBLE_DATE_STRING] |
| 103 | + if len(try_parse) > 0: |
| 104 | + for value in try_parse: |
| 105 | + try: |
| 106 | + parser.parse(str(value)) |
| 107 | + except (ValueError, TypeError, OverflowError): |
| 108 | + is_date = False |
| 109 | + break |
| 110 | + else: |
| 111 | + is_date = False |
| 112 | + |
| 113 | + if is_date: |
| 114 | + df[column] = pd.to_datetime(df[column], errors="coerce", utc=True) |
| 115 | + elif is_integer: |
| 116 | + df[column] = df[column].apply(lambda x: int(atof_custom(str(x))) if pd.notna(x) else x) |
| 117 | + # If there are NaN / blank values, the column will be converted to float |
| 118 | + # Convert it back to integer |
| 119 | + df[column] = df[column].astype("Int64") |
| 120 | + elif is_float: |
| 121 | + df[column] = df[column].apply(lambda x: atof_custom(str(x)) if pd.notna(x) else x) |
| 122 | + else: |
| 123 | + inferred_type = pd.api.types.infer_dtype(values) |
| 124 | + if inferred_type == "integer": |
| 125 | + df[column] = pd.to_numeric(df[column], errors="coerce", downcast="integer") |
| 126 | + elif inferred_type == "floating": |
| 127 | + df[column] = pd.to_numeric(df[column], errors="coerce") |
| 128 | + |
| 129 | + return df |
| 130 | + |
| 131 | + except pd.errors.ParserError as e: |
| 132 | + return str(e) |
0 commit comments