low-code / files /04_topicos /etapa_08_analisar_macrotemas.py
brutalpizza2's picture
Upload 51 files
979753a verified
from __future__ import annotations
import sys
from pathlib import Path
ROOT_DIR = Path(__file__).resolve().parents[1]
if str(ROOT_DIR) not in sys.path:
sys.path.insert(0, str(ROOT_DIR))
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pipeline_00_config import (
MACROTHEME_TEMPORAL_PDF,
MACROTHEME_TEMPORAL_PNG,
MACROTHEMES,
STUDY_END,
STUDY_START,
TOPICS_TO_REMOVE,
TOPIC_ALIGNED_COMMENTS_CSV,
ensure_directories,
parse_utc_datetime,
read_csv_with_fallback,
)
def map_macrotheme(topic_id: int) -> str | None:
for macrotheme, topic_ids in MACROTHEMES.items():
if topic_id in topic_ids:
return macrotheme
return None
def main() -> None:
ensure_directories()
aligned = read_csv_with_fallback(TOPIC_ALIGNED_COMMENTS_CSV, low_memory=False)
aligned["topic_id"] = pd.to_numeric(aligned["topic_id"], errors="coerce")
aligned["published_at"] = parse_utc_datetime(aligned["published_at"])
aligned = aligned.dropna(subset=["topic_id", "published_at"]).copy()
aligned["topic_id"] = aligned["topic_id"].astype(int)
excluded_topics = set(TOPICS_TO_REMOVE + [-1])
aligned = aligned.loc[~aligned["topic_id"].isin(excluded_topics)].copy()
aligned["macrotheme"] = aligned["topic_id"].apply(map_macrotheme)
aligned = aligned.dropna(subset=["macrotheme"]).copy()
aligned["mes_ano"] = aligned["published_at"].dt.to_period("M")
counts = aligned.groupby(["mes_ano", "macrotheme"]).size().reset_index(name="count")
pivot = counts.pivot_table(index="mes_ano", columns="macrotheme", values="count", fill_value=0)
full_range = pd.period_range(start=STUDY_START, end=STUDY_END, freq="M")
pivot = pivot.reindex(full_range, fill_value=0)
proportions = pivot.div(pivot.sum(axis=1).replace(0, 1), axis=0)
plt.figure(figsize=(12, 6))
for macrotheme in proportions.columns:
plt.plot(proportions.index.astype(str), proportions[macrotheme], label=macrotheme)
tick_positions = np.arange(0, len(proportions.index), 6)
plt.xticks(tick_positions, proportions.index.astype(str)[tick_positions], rotation=45, ha="right")
plt.title("Evolucao temporal dos macrotemas")
plt.xlabel("Mes")
plt.ylabel("Proporcao de comentarios")
plt.legend(ncol=2, frameon=False)
plt.tight_layout()
plt.savefig(MACROTHEME_TEMPORAL_PNG, dpi=300)
plt.savefig(MACROTHEME_TEMPORAL_PDF)
plt.close()
print(f"Grafico salvo em: {MACROTHEME_TEMPORAL_PNG}")
if __name__ == "__main__":
main()