datfid 0.1.12__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.
datfid/__init__.py ADDED
@@ -0,0 +1 @@
1
+ from .client import DATFIDClient
datfid/client.py ADDED
@@ -0,0 +1,146 @@
1
+ import requests
2
+ import pandas as pd
3
+ from typing import Dict, Any, Optional, Union
4
+ import json
5
+ from types import SimpleNamespace
6
+ import tempfile
7
+ import os
8
+ import gc
9
+ import psutil
10
+ import logging
11
+
12
+ class DATFIDClient:
13
+ def __init__(self, token: str):
14
+ self.api_url = "https://datfid-org-datfid-sdk.hf.space/"
15
+ self.headers = {"Authorization": f"Bearer {token}"}
16
+ self.logger = logging.getLogger(__name__)
17
+
18
+ def _cleanup_memory(self):
19
+ """Clean up memory after operations"""
20
+ gc.collect()
21
+ if hasattr(psutil, 'Process'):
22
+ process = psutil.Process()
23
+ try:
24
+ process.memory_info().rss # Force memory info update
25
+ except:
26
+ pass
27
+
28
+ def ping(self):
29
+ try:
30
+ response = requests.get(self.api_url, headers=self.headers).json()
31
+ self._cleanup_memory()
32
+ return response
33
+ except Exception as e:
34
+ self.logger.error(f"Ping failed: {str(e)}")
35
+ raise
36
+
37
+ def secure_ping(self):
38
+ try:
39
+ response = requests.get(f"{self.api_url}secure-ping/", headers=self.headers).json()
40
+ self._cleanup_memory()
41
+ return response
42
+ except Exception as e:
43
+ self.logger.error(f"Secure ping failed: {str(e)}")
44
+ raise
45
+
46
+ def fit_model(
47
+ self,
48
+ df: pd.DataFrame,
49
+ id_col: str,
50
+ time_col: str,
51
+ y: str,
52
+ lag_y: Optional[Union[int, str, list[int]]] = None,
53
+ lagged_features: Optional[Dict[str, int]] = None,
54
+ current_features: Optional[list] = None,
55
+ filter_by_significance: bool = False,
56
+ meanvar_test: bool = False
57
+ ) -> SimpleNamespace:
58
+ """
59
+ Fit a model using the DATFID API.
60
+
61
+ Args:
62
+ df: DataFrame containing the data
63
+ id_col: Name of the ID column
64
+ time_col: Name of the time column
65
+ y: Name of the target variable
66
+ lagged_features: Dictionary of features and their lag values
67
+ current_features: List of current features to use
68
+ filter_by_significance: Whether to filter features by significance
69
+ meanvar_test: Whether to perform mean-variance test
70
+
71
+ Returns:
72
+ SimpleNamespace containing the model fit results
73
+ """
74
+
75
+ df = df.copy()
76
+ for col in df.columns:
77
+ if pd.api.types.is_datetime64_any_dtype(df[col]):
78
+ df[col] = df[col].astype(str)
79
+
80
+ data = {
81
+ "df": df.to_dict(orient="records"),
82
+ "id_col": id_col,
83
+ "time_col": time_col,
84
+ "y": y,
85
+ "lag_y": lag_y,
86
+ "lagged_features": lagged_features or {},
87
+ "current_features": current_features or [],
88
+ "filter_by_significance": filter_by_significance,
89
+ "meanvar_test": meanvar_test
90
+ }
91
+
92
+ response = requests.post(
93
+ f"{self.api_url}modelfit/",
94
+ json=data,
95
+ headers=self.headers
96
+ )
97
+
98
+ if response.status_code != 200:
99
+ raise Exception(f"Model fit failed: {response.text}")
100
+
101
+ result_dict = response.json()
102
+ return SimpleNamespace(**result_dict)
103
+
104
+ def forecast_model(
105
+ self,
106
+ df_forecast: pd.DataFrame
107
+ ) -> pd.DataFrame:
108
+ """
109
+ Generate forecasts using the fitted model.
110
+
111
+ Args:
112
+ df_forecast: DataFrame containing the forecast data
113
+
114
+ Returns:
115
+ DataFrame containing the forecast results
116
+ """
117
+
118
+ try:
119
+ df_forecast = df_forecast.copy()
120
+ for col in df_forecast.columns:
121
+ if pd.api.types.is_datetime64_any_dtype(df_forecast[col]):
122
+ df_forecast[col] = df_forecast[col].astype(str)
123
+
124
+ # Convert DataFrame to list of records
125
+ data = df_forecast.to_dict(orient="records")
126
+
127
+ response = requests.post(
128
+ f"{self.api_url}modelforecast/",
129
+ json=data,
130
+ headers=self.headers
131
+ )
132
+
133
+ if response.status_code != 200:
134
+ raise Exception(f"Forecast generation failed: {response.text}")
135
+
136
+ result = pd.DataFrame(response.json())
137
+
138
+ # Clean up memory after operation
139
+ del df_forecast
140
+ del data
141
+ self._cleanup_memory()
142
+
143
+ return result
144
+ except Exception as e:
145
+ self.logger.error(f"Forecast generation failed: {str(e)}")
146
+ raise
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.4
2
+ Name: datfid
3
+ Version: 0.1.12
4
+ Summary: SDK to access the DATFID API hosted on Hugging Face Spaces
5
+ Author: DATFID
6
+ Author-email: igor.schapiro@datfid.com
7
+ License: MIT
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Programming Language :: Python :: 3
10
+ Requires-Python: >=3.7
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: requests>=2.31.0
14
+ Requires-Dist: pandas>=1.0.1
15
+ Requires-Dist: numpy<2.1,>=1.22
16
+ Dynamic: author
17
+ Dynamic: author-email
18
+ Dynamic: classifier
19
+ Dynamic: description
20
+ Dynamic: description-content-type
21
+ Dynamic: license
22
+ Dynamic: license-file
23
+ Dynamic: requires-dist
24
+ Dynamic: requires-python
25
+ Dynamic: summary
26
+
27
+ # DATFID SDK
28
+
29
+ A Python SDK to access the DATFID API running on Hugging Face Spaces.
30
+
31
+ ## Installation
32
+
33
+ ```bash
34
+ pip install datfid
35
+ ```
36
+
37
+ ## Usage
38
+
39
+ ```python
40
+ from datfid import DATFIDClient
41
+
42
+ # Initialize the client with your Hugging Face token
43
+ client = DATFIDClient(token="your_huggingface_token")
44
+
45
+ # Fit a model
46
+ fit_result = client.fit_model(
47
+ file_path="path/to/your/data.xlsx",
48
+ id_col="Individual",
49
+ time_col="Time",
50
+ y="Loan Probability",
51
+ lagged_features={"Repayment Amount": 1, "Missed Payments": 2},
52
+ current_features=["Credit Score", "Unemployment Rate"],
53
+ filter_by_significance=True,
54
+ meanvar_test=False
55
+ )
56
+
57
+ # Generate forecasts
58
+ forecast_df = client.generate_forecast(
59
+ file_path="path/to/your/forecast_data.xlsx",
60
+ id_col="Individual",
61
+ time_col="Time",
62
+ y="Loan Probability",
63
+ lagged_features={"Repayment Amount": 1, "Missed Payments": 2},
64
+ current_features=["Credit Score", "Unemployment Rate"],
65
+ filter_by_significance=True,
66
+ meanvar_test=False
67
+ )
68
+
69
+ # The forecast DataFrame includes the original data plus forecast columns:
70
+ # - forecast: The predicted values
71
+ # - forecast_lower: Lower bound of the prediction interval
72
+ # - forecast_upper: Upper bound of the prediction interval
73
+ # - forecast_error: Standard error of the forecast
74
+ ```
75
+
76
+ ## API Reference
77
+
78
+ ### DATFIDClient
79
+
80
+ #### `__init__(token: str)`
81
+ Initialize the client with your Hugging Face token.
82
+
83
+ #### `fit_model(file_path: str, id_col: str, time_col: str, y: str, lagged_features: Optional[Dict[str, int]] = None, current_features: Optional[list] = None, filter_by_significance: bool = False, meanvar_test: bool = False) -> Dict[str, Any]`
84
+ Fit a model using the provided data.
85
+
86
+ #### `generate_forecast(file_path: str, id_col: str, time_col: str, y: str, lagged_features: Optional[Dict[str, int]] = None, current_features: Optional[list] = None, filter_by_significance: bool = False, meanvar_test: bool = False) -> pd.DataFrame`
87
+ Generate forecasts using the fitted model.
@@ -0,0 +1,7 @@
1
+ datfid/__init__.py,sha256=PojdUQsimZvawR8lgqVpzs3EkRtkA7iwuDk7fovJF54,34
2
+ datfid/client.py,sha256=XH8wTBsHOHT3Fl1DzDWP9PfIUxJGg24eLH7_cWuymic,4656
3
+ datfid-0.1.12.dist-info/licenses/LICENSE,sha256=5b2JLb1-P8Nt919phjUmP0umS82SxGMlIF2QFn9ILgM,1084
4
+ datfid-0.1.12.dist-info/METADATA,sha256=cTQxUumLGxbsYwS09JxmJJrOIcit1ZCgeKE-nenwd-I,2750
5
+ datfid-0.1.12.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
6
+ datfid-0.1.12.dist-info/top_level.txt,sha256=VFG23u9NMNQJ8S_IFfW-S5d8oSUd71SFA346ovh_uxA,7
7
+ datfid-0.1.12.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) 2025 DATFID
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
+ datfid