temperature-index 0.3.1__tar.gz

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.
@@ -0,0 +1,59 @@
1
+ Metadata-Version: 2.4
2
+ Name: temperature-index
3
+ Version: 0.3.1
4
+ Summary: Temperature index for news media coverage
5
+ Author-email: Irakli Janiashvili <irakli.janiashvili@gmail.com>
6
+ Requires-Python: <4.0,>=3.12
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: pandas<4,>=3.1.1
9
+ Requires-Dist: scikit-learn<2.0.0,>=1.6.0
10
+ Requires-Dist: umap-learn<1.0.0,>=0.5.7
11
+ Requires-Dist: requests<3.0.0,>=2.32.3
12
+
13
+ # temperature-index
14
+
15
+ Temperature-index calculations for news media. Version 0.3.1 requires
16
+ Python 3.12+ and pandas 3.1.1+.
17
+
18
+ ## Install
19
+
20
+ Add the published package to a uv project:
21
+
22
+ ```sh
23
+ uv add 'temperature-index==0.3.1'
24
+ uv run python -c 'import aladeen_media_indexer.temperature_index'
25
+ ```
26
+
27
+ This package does not require the Temporal application or its workspace to
28
+ install. Its runtime dependencies are declared in the package metadata. No
29
+ package-specific environment file, database credentials or demo service is
30
+ required to install or import it. Running application scoring/SQL is separate.
31
+
32
+ ## Development and offline smoke test
33
+
34
+ Use uv with the checked-in `uv.lock`. `.python-version` selects Python 3.12.16;
35
+ `UV_PYTHON` can select an already-installed interpreter. From this repository:
36
+
37
+ ```sh
38
+ uv sync --frozen --no-dev --no-editable
39
+ uv run --frozen --no-dev --no-editable python -I -B -m unittest discover -s tests -p 'test_smoke.py'
40
+ uv build --no-sources
41
+ ```
42
+
43
+ `--no-editable` tests the installed package rather than an editable checkout.
44
+ The test checks count/diversity/velocity on tiny owned data and a hand-worked
45
+ normalized PCA score. It uses no database, credentials, external API or model.
46
+ Python-level socket calls are denied; remote execution also needs an outer
47
+ network/resource sandbox. The original optional dev group is retained separately
48
+ and is not required for runtime or the smoke test. Passing this fixture does not
49
+ validate production histories, application SQL or a deployment.
50
+
51
+ ## Release changes
52
+
53
+ The distribution name changes from `aladeen-media-indexer` to `temperature-index`.
54
+ The Python import is still `aladeen_media_indexer`. Replace the old dependency
55
+ in a fresh environment; don't install both distributions, since they provide
56
+ the same module files. The unrelated `media-indexer` project is not this library.
57
+
58
+ The pandas requirement now accepts the supported pandas 3 range instead of
59
+ pinning pandas 2.1.4. The calculation implementation is unchanged from 0.3.0.
@@ -0,0 +1,47 @@
1
+ # temperature-index
2
+
3
+ Temperature-index calculations for news media. Version 0.3.1 requires
4
+ Python 3.12+ and pandas 3.1.1+.
5
+
6
+ ## Install
7
+
8
+ Add the published package to a uv project:
9
+
10
+ ```sh
11
+ uv add 'temperature-index==0.3.1'
12
+ uv run python -c 'import aladeen_media_indexer.temperature_index'
13
+ ```
14
+
15
+ This package does not require the Temporal application or its workspace to
16
+ install. Its runtime dependencies are declared in the package metadata. No
17
+ package-specific environment file, database credentials or demo service is
18
+ required to install or import it. Running application scoring/SQL is separate.
19
+
20
+ ## Development and offline smoke test
21
+
22
+ Use uv with the checked-in `uv.lock`. `.python-version` selects Python 3.12.16;
23
+ `UV_PYTHON` can select an already-installed interpreter. From this repository:
24
+
25
+ ```sh
26
+ uv sync --frozen --no-dev --no-editable
27
+ uv run --frozen --no-dev --no-editable python -I -B -m unittest discover -s tests -p 'test_smoke.py'
28
+ uv build --no-sources
29
+ ```
30
+
31
+ `--no-editable` tests the installed package rather than an editable checkout.
32
+ The test checks count/diversity/velocity on tiny owned data and a hand-worked
33
+ normalized PCA score. It uses no database, credentials, external API or model.
34
+ Python-level socket calls are denied; remote execution also needs an outer
35
+ network/resource sandbox. The original optional dev group is retained separately
36
+ and is not required for runtime or the smoke test. Passing this fixture does not
37
+ validate production histories, application SQL or a deployment.
38
+
39
+ ## Release changes
40
+
41
+ The distribution name changes from `aladeen-media-indexer` to `temperature-index`.
42
+ The Python import is still `aladeen_media_indexer`. Replace the old dependency
43
+ in a fresh environment; don't install both distributions, since they provide
44
+ the same module files. The unrelated `media-indexer` project is not this library.
45
+
46
+ The pandas requirement now accepts the supported pandas 3 range instead of
47
+ pinning pandas 2.1.4. The calculation implementation is unchanged from 0.3.0.
@@ -0,0 +1,132 @@
1
+ import pandas as pd
2
+ from abc import ABC, abstractmethod
3
+ from typing import Any
4
+ import requests
5
+
6
+
7
+ class Metric(ABC):
8
+ @abstractmethod
9
+ def calculate(self, df: pd.DataFrame) -> pd.Series:
10
+ pass
11
+
12
+ def get7ma(self, df: pd.DataFrame) -> pd.Series:
13
+ return df.rolling(window=7).mean()
14
+
15
+
16
+ class ArticleCountMetric(Metric):
17
+ def calculate(self, df: pd.DataFrame) -> pd.Series:
18
+ return df.groupby("day").size()
19
+
20
+
21
+ class EngagementRateMetric(Metric):
22
+ def calculate(self, df: pd.DataFrame) -> pd.Series:
23
+ return df.groupby("day")["engagement"].mean()
24
+
25
+
26
+ class SourceDiversityMetric(Metric):
27
+ def calculate(self, df: pd.DataFrame) -> pd.Series:
28
+ return df.groupby("day")["source"].nunique()
29
+
30
+
31
+ class ArticleVelocityMetric(Metric):
32
+ def calculate(self, df: pd.DataFrame) -> pd.Series:
33
+ return df.groupby("day").size().diff()
34
+
35
+
36
+ class MomentumMetric(Metric):
37
+ # Divide today's engagement by the 7-day moving average of engagement
38
+ def calculate(self, df: pd.DataFrame) -> pd.Series:
39
+ return (
40
+ df.groupby("day")["engagement"].sum()
41
+ / df.groupby("day")["engagement"].rolling(window=7).mean().mean()
42
+ )
43
+
44
+
45
+ class WeekEngagementDifferenceMetric(Metric):
46
+ def calculate(self, df: pd.DataFrame) -> pd.Series:
47
+ # Calculate the engagement for each day
48
+ daily_engagement = df.groupby("day")["engagement"].sum()
49
+
50
+ # Shift the daily engagement by 7 days to align with the previous week
51
+ prev_week_engagement = daily_engagement.shift(7)
52
+
53
+ # Calculate the difference in engagement from the same day last week
54
+ week_difference = daily_engagement - prev_week_engagement
55
+
56
+ return week_difference
57
+
58
+
59
+ class EngagementCountMetric(Metric):
60
+ def calculate(self, df: pd.DataFrame) -> pd.Series:
61
+ return df.groupby("day")["engagement"].count()
62
+
63
+
64
+ class TopicSimilarityMetric(Metric):
65
+ def __init__(self, title_embeddings: Any) -> None:
66
+ self.title_embeddings = title_embeddings
67
+
68
+ def calculate(self, df: pd.DataFrame) -> pd.Series:
69
+ # Implement the topic similarity calculation logic here
70
+ raise NotImplementedError("Topic similarity calculation not implemented")
71
+
72
+
73
+ # WIP
74
+ class GELUSDExchangeRateMetric(Metric):
75
+ def __init__(self, api_key: str) -> None:
76
+ self.api_key = api_key
77
+
78
+ def calculate(self, df: pd.DataFrame) -> pd.Series:
79
+ # Get the start and end dates from the input DataFrame
80
+ start_date = pd.to_datetime(df["day"].min())
81
+ end_date = pd.to_datetime(df["day"].max())
82
+
83
+ # Set up the API endpoint and parameters
84
+ url = "https://www.alphavantage.co/query"
85
+ params = {
86
+ "function": "FX_DAILY",
87
+ "from_symbol": "GEL",
88
+ "to_symbol": "USD",
89
+ "apikey": self.api_key,
90
+ "outputsize": "full",
91
+ }
92
+
93
+ # Make the API request
94
+ response = requests.get(url, params=params)
95
+ data = response.json()
96
+
97
+ # Check if the API request was successful
98
+ if "Error Message" in data:
99
+ raise ValueError(f"API request failed: {data['Error Message']}")
100
+
101
+ # Extract the exchange rate data
102
+ exchange_rates = data["Time Series FX (Daily)"]
103
+
104
+ # Convert the exchange rate data to a DataFrame
105
+ exchange_rate_df = pd.DataFrame.from_dict(
106
+ exchange_rates, orient="index", columns=["4. close"]
107
+ )
108
+ exchange_rate_df.index = pd.to_datetime(exchange_rate_df.index)
109
+ exchange_rate_df.columns = ["GEL/USD"]
110
+
111
+ # Filter the exchange rate data based on the input DataFrame's date range
112
+ mask = (exchange_rate_df.index >= start_date) & (
113
+ exchange_rate_df.index <= end_date
114
+ )
115
+ exchange_rate_series = exchange_rate_df.loc[mask, "GEL/USD"]
116
+ # convert to float
117
+ exchange_rate_series = exchange_rate_series.astype(float)
118
+
119
+ # Check if the filtered series is empty
120
+ if exchange_rate_series.empty:
121
+ print(
122
+ f"No exchange rate data found for the date range: {start_date} to {end_date}"
123
+ )
124
+ print("Available exchange rate data:")
125
+ print(exchange_rate_df)
126
+
127
+ # fill missing values with the previous value
128
+ # exchange_rate_series = exchange_rate_series.ffill()
129
+ # exchange_rate_series = exchange_rate_series.bfill()
130
+ print(exchange_rate_series)
131
+
132
+ return exchange_rate_series
@@ -0,0 +1,143 @@
1
+ import pandas as pd
2
+ from abc import ABC, abstractmethod
3
+ from typing import List, Dict
4
+ from aladeen_media_indexer.metrics import Metric
5
+ import numpy as np
6
+ from sklearn.preprocessing import StandardScaler
7
+ from sklearn.impute import SimpleImputer
8
+ from sklearn.decomposition import PCA
9
+
10
+
11
+ class Index(ABC):
12
+ def __init__(self, metrics: List[Metric]) -> None:
13
+ self.metrics = metrics
14
+ # self.weights = weights
15
+ self.index: pd.DataFrame = None
16
+
17
+ @abstractmethod
18
+ def calculate_scores(self, df: pd.DataFrame) -> None:
19
+ pass
20
+
21
+ @abstractmethod
22
+ def display_top_news(self, top_n: int = 10) -> None:
23
+ pass
24
+
25
+
26
+ class TemperatureIndex(Index):
27
+ def __init__(
28
+ self,
29
+ metrics: List[Metric],
30
+ min_articles_per_day: int = 400,
31
+ dimensionality_reduction=None,
32
+ ) -> None:
33
+ super().__init__(metrics)
34
+ self.min_articles_per_day = min_articles_per_day
35
+ if dimensionality_reduction is None:
36
+ self.dimensionality_reduction = PCA(n_components=1)
37
+ else:
38
+ self.dimensionality_reduction = dimensionality_reduction
39
+
40
+ def filter_data(self, df: pd.DataFrame) -> pd.DataFrame:
41
+ # Convert 'day' column to Timestamp
42
+ df["day"] = pd.to_datetime(df["day"])
43
+
44
+ # Filter out days with less than min_articles_per_day
45
+ article_counts = df.groupby("day").size()
46
+ valid_days = article_counts[article_counts >= self.min_articles_per_day].index
47
+ df_filtered = df[df["day"].isin(valid_days)]
48
+
49
+ return df_filtered
50
+
51
+ def calculate_metric_values(self, df: pd.DataFrame) -> Dict[str, pd.Series]:
52
+ metric_values = {}
53
+ for metric in self.metrics:
54
+ metric_values[metric.__class__.__name__] = metric.calculate(df)
55
+
56
+ return metric_values
57
+
58
+ def create_temperature_index(
59
+ self, metric_values: Dict[str, pd.Series]
60
+ ) -> pd.DataFrame:
61
+ temperature_index = pd.DataFrame(metric_values)
62
+ return temperature_index
63
+
64
+ def handle_missing_values(self, temperature_index: pd.DataFrame) -> np.ndarray:
65
+ imputer = SimpleImputer(strategy="mean")
66
+ imputed_data = imputer.fit_transform(temperature_index)
67
+ return imputed_data
68
+
69
+ def standardize_data(self, imputed_data: np.ndarray) -> np.ndarray:
70
+ scaler = StandardScaler()
71
+ scaled_data = scaler.fit_transform(imputed_data)
72
+ return scaled_data
73
+
74
+ def perform_pca(self, scaled_data: np.ndarray) -> np.ndarray:
75
+ pca = PCA(
76
+ n_components=1
77
+ ) # Set the number of components to 1 for a single index
78
+ pca.fit(scaled_data)
79
+ principal_component_scores = pca.transform(scaled_data)
80
+ return principal_component_scores
81
+
82
+ def normalize_index(self, temperature_index: pd.DataFrame) -> pd.DataFrame:
83
+ min_max_scaler = lambda x: (x - x.min()) / (x.max() - x.min())
84
+ normalized_index = temperature_index.apply(min_max_scaler)
85
+ return normalized_index
86
+
87
+ def perform_dimensionality_reduction(self, scaled_data: np.ndarray) -> np.ndarray:
88
+ self.dimensionality_reduction.fit(scaled_data)
89
+ reduced_data = self.dimensionality_reduction.transform(scaled_data)
90
+ return reduced_data
91
+
92
+ def calculate_scores(
93
+ self, df: pd.DataFrame, smoothing_function=(lambda x: x)
94
+ ) -> None:
95
+ # Filter the data
96
+ filtered_df = self.filter_data(df)
97
+
98
+ # Calculate metric values
99
+ metric_values = self.calculate_metric_values(filtered_df)
100
+
101
+ # Create temperature index dataframe
102
+ temperature_index = self.create_temperature_index(metric_values)
103
+
104
+ smoothed_index = smoothing_function(temperature_index)
105
+
106
+ # Get first non-NaN index to use as a reference for missing values
107
+ first_non_nan_index = smoothed_index.apply(lambda x: x.first_valid_index())
108
+
109
+ smoothed_index = smoothed_index.loc[
110
+ first_non_nan_index["ArticleCountMetric"] : smoothed_index.index[-2]
111
+ ]
112
+
113
+ # Handle missing values
114
+ imputed_data = self.handle_missing_values(smoothed_index)
115
+
116
+ # Standardize the data
117
+ scaled_data = self.standardize_data(imputed_data)
118
+
119
+ # Perform dimensionality reduction
120
+ reduced_data = self.perform_dimensionality_reduction(scaled_data)
121
+
122
+ # Add the reduced data scores to the temperature index dataframe
123
+ smoothed_index.loc[:, "temperature_score"] = reduced_data
124
+
125
+ # Normalize the index
126
+ normalized_index = self.normalize_index(smoothed_index)
127
+
128
+ self.index = normalized_index
129
+
130
+ def display_top_news(self, top_n: int = 10) -> None:
131
+ if self.index is None:
132
+ raise ValueError(
133
+ "Temperature index not calculated. Call calculate_scores() first."
134
+ )
135
+
136
+ # Display the top news articles based on the temperature score
137
+ top_news = self.index.sort_values(by="temperature_score", ascending=False).head(
138
+ top_n
139
+ )
140
+ print(top_news)
141
+
142
+ def get_index(self):
143
+ return self.index["temperature_score"]
@@ -0,0 +1,13 @@
1
+ import pandas as pd
2
+
3
+
4
+ def apply_smoothing(df: pd.DataFrame, window=7, smoothing_value=3):
5
+ rolling_averages = df.rolling(window=window, win_type="exponential").mean(
6
+ tau=smoothing_value
7
+ )
8
+
9
+ # Apply min-max scaling to normalize the rolling averages
10
+ min_max_scaler = lambda x: (x - x.min()) / (x.max() - x.min())
11
+ rolling_averages = rolling_averages.apply(min_max_scaler)
12
+
13
+ return rolling_averages
@@ -0,0 +1,30 @@
1
+ [project]
2
+ name = "temperature-index"
3
+ description = "Temperature index for news media coverage"
4
+ version = "0.3.1"
5
+ readme = "README.md"
6
+ authors = [
7
+ {name = "Irakli Janiashvili", email = "irakli.janiashvili@gmail.com"},
8
+ ]
9
+ requires-python = "<4.0,>=3.12"
10
+ dependencies = [
11
+ "pandas>=3.1.1,<4",
12
+ "scikit-learn<2.0.0,>=1.6.0",
13
+ "umap-learn<1.0.0,>=0.5.7",
14
+ "requests<3.0.0,>=2.32.3",
15
+ ]
16
+
17
+ [dependency-groups]
18
+ dev = [
19
+ "streamlit<2.0.0,>=1.41.0",
20
+ "psycopg2<3.0.0,>=2.9.10",
21
+ "sqlalchemy<3.0.0,>=2.0.36",
22
+ "streamlit-echarts<1.0.0,>=0.4.0",
23
+ ]
24
+
25
+ [build-system]
26
+ requires = ["setuptools", "wheel"]
27
+ build-backend = "setuptools.build_meta"
28
+
29
+ [tool.setuptools]
30
+ packages = ["aladeen_media_indexer"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,59 @@
1
+ Metadata-Version: 2.4
2
+ Name: temperature-index
3
+ Version: 0.3.1
4
+ Summary: Temperature index for news media coverage
5
+ Author-email: Irakli Janiashvili <irakli.janiashvili@gmail.com>
6
+ Requires-Python: <4.0,>=3.12
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: pandas<4,>=3.1.1
9
+ Requires-Dist: scikit-learn<2.0.0,>=1.6.0
10
+ Requires-Dist: umap-learn<1.0.0,>=0.5.7
11
+ Requires-Dist: requests<3.0.0,>=2.32.3
12
+
13
+ # temperature-index
14
+
15
+ Temperature-index calculations for news media. Version 0.3.1 requires
16
+ Python 3.12+ and pandas 3.1.1+.
17
+
18
+ ## Install
19
+
20
+ Add the published package to a uv project:
21
+
22
+ ```sh
23
+ uv add 'temperature-index==0.3.1'
24
+ uv run python -c 'import aladeen_media_indexer.temperature_index'
25
+ ```
26
+
27
+ This package does not require the Temporal application or its workspace to
28
+ install. Its runtime dependencies are declared in the package metadata. No
29
+ package-specific environment file, database credentials or demo service is
30
+ required to install or import it. Running application scoring/SQL is separate.
31
+
32
+ ## Development and offline smoke test
33
+
34
+ Use uv with the checked-in `uv.lock`. `.python-version` selects Python 3.12.16;
35
+ `UV_PYTHON` can select an already-installed interpreter. From this repository:
36
+
37
+ ```sh
38
+ uv sync --frozen --no-dev --no-editable
39
+ uv run --frozen --no-dev --no-editable python -I -B -m unittest discover -s tests -p 'test_smoke.py'
40
+ uv build --no-sources
41
+ ```
42
+
43
+ `--no-editable` tests the installed package rather than an editable checkout.
44
+ The test checks count/diversity/velocity on tiny owned data and a hand-worked
45
+ normalized PCA score. It uses no database, credentials, external API or model.
46
+ Python-level socket calls are denied; remote execution also needs an outer
47
+ network/resource sandbox. The original optional dev group is retained separately
48
+ and is not required for runtime or the smoke test. Passing this fixture does not
49
+ validate production histories, application SQL or a deployment.
50
+
51
+ ## Release changes
52
+
53
+ The distribution name changes from `aladeen-media-indexer` to `temperature-index`.
54
+ The Python import is still `aladeen_media_indexer`. Replace the old dependency
55
+ in a fresh environment; don't install both distributions, since they provide
56
+ the same module files. The unrelated `media-indexer` project is not this library.
57
+
58
+ The pandas requirement now accepts the supported pandas 3 range instead of
59
+ pinning pandas 2.1.4. The calculation implementation is unchanged from 0.3.0.
@@ -0,0 +1,12 @@
1
+ README.md
2
+ pyproject.toml
3
+ aladeen_media_indexer/__init__.py
4
+ aladeen_media_indexer/metrics.py
5
+ aladeen_media_indexer/temperature_index.py
6
+ aladeen_media_indexer/utils.py
7
+ temperature_index.egg-info/PKG-INFO
8
+ temperature_index.egg-info/SOURCES.txt
9
+ temperature_index.egg-info/dependency_links.txt
10
+ temperature_index.egg-info/requires.txt
11
+ temperature_index.egg-info/top_level.txt
12
+ tests/test_smoke.py
@@ -0,0 +1,4 @@
1
+ pandas<4,>=3.1.1
2
+ scikit-learn<2.0.0,>=1.6.0
3
+ umap-learn<1.0.0,>=0.5.7
4
+ requests<3.0.0,>=2.32.3
@@ -0,0 +1 @@
1
+ aladeen_media_indexer
@@ -0,0 +1,66 @@
1
+ """Offline public-API smoke: count/diversity/velocity and a known PCA index."""
2
+
3
+ import unittest
4
+ from importlib import metadata
5
+ from unittest.mock import patch
6
+
7
+
8
+ def deny_network(*args, **kwargs):
9
+ raise AssertionError("Offline smoke attempted network access")
10
+
11
+
12
+ class MediaIndexerSmokeTests(unittest.TestCase):
13
+ def setUp(self):
14
+ for name in [
15
+ "socket.socket.connect",
16
+ "socket.socket.connect_ex",
17
+ "socket.create_connection",
18
+ "socket.getaddrinfo",
19
+ ]:
20
+ guard = patch(name, side_effect=deny_network)
21
+ guard.start()
22
+ self.addCleanup(guard.stop)
23
+
24
+ def test_public_metrics_and_known_normalized_index(self):
25
+ import numpy as np
26
+ import pandas as pd
27
+ from aladeen_media_indexer.metrics import (
28
+ ArticleCountMetric,
29
+ ArticleVelocityMetric,
30
+ SourceDiversityMetric,
31
+ )
32
+ from aladeen_media_indexer.temperature_index import TemperatureIndex
33
+
34
+ self.assertEqual(metadata.version("temperature-index"), "0.3.1")
35
+ counts = [1, 2, 4, 7, 11, 16, 22, 29]
36
+ days = pd.date_range("2026-01-01", periods=8)
37
+ data = pd.DataFrame(
38
+ [
39
+ {"day": day, "source": f"owned-source-{i % min(d + 1, 3)}"}
40
+ for d, (day, count) in enumerate(zip(days, counts))
41
+ for i in range(count)
42
+ ]
43
+ )
44
+ self.assertEqual(ArticleCountMetric().calculate(data).tolist(), counts)
45
+ self.assertEqual(
46
+ SourceDiversityMetric().calculate(data).tolist(), [1, 2, 3, 3, 3, 3, 3, 3]
47
+ )
48
+ velocity = ArticleVelocityMetric().calculate(data)
49
+ self.assertTrue(np.isnan(velocity.iloc[0]))
50
+ self.assertEqual(velocity.iloc[1:].tolist(), [1, 2, 3, 4, 5, 6, 7])
51
+ index = TemperatureIndex([ArticleCountMetric()], min_articles_per_day=1)
52
+ index.calculate_scores(data)
53
+ result = index.get_index()
54
+ self.assertEqual(list(result.index), list(days[:7]))
55
+ # One PCA dimension preserves order. Existing API omits the last day;
56
+ # counts 1..22 normalize to these independently worked values.
57
+ np.testing.assert_allclose(
58
+ result.to_numpy(),
59
+ [0, 1 / 21, 3 / 21, 6 / 21, 10 / 21, 15 / 21, 1],
60
+ atol=1e-12,
61
+ rtol=0,
62
+ )
63
+
64
+
65
+ if __name__ == "__main__":
66
+ unittest.main()