A·B라인 생산 일보 | 2025년 3–4월

요약

3월에서 4월 사이 A라인 월 생산량은 5,820 kg 늘고 가동률은 4.26%p 하락했습니다. B라인은 26,300 kg, 4.71%p 올랐습니다. daily_report.xlsx의 3월·4월 날짜 행 기준입니다.

4월 A라인 생산량

264,160 kg

21개 날짜 행에 기록된 생산량 합계. t는 1,000을 곱해 kg으로 환산. 합계 지표에는 분자와 분모가 적용되지 않음.

4월 A라인 가동률

89.55 %

실제 가동시간 394시간 ÷ 계획 가동시간 440시간 × 100. 계획은 날짜 행 22개 × 20시간이며 보전일 포함.

4월 B라인 생산량

237,700 kg

22개 날짜 행에 기록된 생산량 합계. t는 1,000을 곱해 kg으로 환산. 합계 지표에는 분자와 분모가 적용되지 않음.

4월 B라인 가동률

86.14 %

실제 가동시간 379시간 ÷ 계획 가동시간 440시간 × 100. 계획은 날짜 행 22개 × 20시간이며 보전일 포함.

두 라인 모두 4월에 월 생산량이 늘었습니다.
3월에서 4월 사이 A라인 가동률은 하락했고 B라인 가동률은 상승했습니다.

차트

3월과 4월의 라인별 월 생산량은 어떻게 달라졌나요?

monthly_production · n = 84

제외 2 · 정기 보전일 생산량 해당 없음

3월과 4월의 라인별 월 생산량은 어떻게 달라졌나요?
관찰
daily_report.xlsx 3월·4월 시트 날짜 행 43개에서 84개 생산량을 합산해 월·라인별 막대 4개를 표시했습니다. 보전일 생산량 2건은 해당 없음으로 합산에서 제외했습니다.
도메인 해석
두 라인 모두 4월에 월 생산량이 늘었습니다.

3월과 4월의 라인별 월 가동률은 어떻게 달라졌나요?

monthly_utilization · n = 86

제외 0

3월과 4월의 라인별 월 가동률은 어떻게 달라졌나요?
관찰
daily_report.xlsx 3월·4월 시트 날짜 행 43개에 기록된 라인별 가동시간 86건을 사용해 월·라인별 막대 4개를 표시했습니다. 제외 0건이며 보전일 0시간을 포함합니다.
도메인 해석
3월에서 4월 사이 A라인 가동률은 하락했고 B라인 가동률은 상승했습니다.

각 라인의 일 생산량은 어떻게 움직였나요?

daily_production · n = 84

제외 2 · 정기 보전일 생산량 해당 없음

각 라인의 일 생산량은 어떻게 움직였나요?
관찰
daily_report.xlsx 3월·4월 시트 일자 행 43개의 라인별 생산량 84건(kg)을 표시했습니다. 보전일 2건과 일보에 없는 주말 16일은 그래프가 끊깁니다.
도메인 해석
기록된 일 생산량 범위는 A라인 11,860~12,900 kg, B라인 10,200~11,100 kg입니다.

가정과 한계

  • 날짜 행 43개에 중복 날짜나 빈 일자·생산량·가동시간 원본 셀이 없었습니다. 생산량 단위는 kg와 t였고, 업무상 해당 없음 2건 외 날짜·수치 파싱 실패는 0건입니다. 가동시간은 보전일 0시간을 포함해 0~20시간입니다. 비고가 빈 날짜 행은 41개입니다.
  • daily_report.xlsx 3월!B17 주간 소계는 62,500 kg이며, B12:B16 날짜 행의 합계는 61,500 kg입니다. 차이 1,000 kg. 두 시트의 월 합계는 날짜 행 집계와 일치합니다.
  • 기록 기간 중 날짜 행이 없는 16일은 모두 주말입니다. 이 날짜는 계획 가동시간에 포함하지 않았습니다. 날짜 행이 있는 보전일은 포함했습니다.
  • 결과의 업무 활용처는 미정입니다. 월별 지표에는 기간 중 날짜 행 수 차이가 반영됩니다.
  • 분포도와 상관관계 그림은 생략했습니다. 일별 그림은 원래 날짜 순서를 보여주며, 요청한 비교는 월별 막대 그림에서 확인할 수 있습니다.

모호성 기록

ID확인 항목상태답변
A01업무 과정해결사용자 설명과 시트 제목에서 생산 현장 일보임을 확인.
근거와 후보
파일 근거
  • daily_report.xlsx 3월!A1:F31, 4월!A1:F32
A02분석 목적과 활용미해결라인별 추이 비교 요청. 활용처는 사용자 답변 ‘모르겠어요’로 미정.
근거와 후보
질문
라인별 월 생산량과 가동률을 비교한 결과를 어디에 쓰실 예정인가요?
파일 근거
  • daily_report.xlsx 3월!A1:F31, 4월!A1:F32
후보 답변
  • 월간 실적 공유
  • 생산계획 조정
  • 설비 보전 검토
영향 범위
  • 결과 활용처
A03행과 머리글해결사용자가 날짜가 있는 행을 지정. 원본 4행은 그룹명과 일자·비고, 5행은 라인별 필드명. 날짜 한 행에 두 라인 기록.
근거와 후보
파일 근거
  • daily_report.xlsx 3월·4월!A4:F5
후보 답변
  • 날짜 행
  • 소계·합계 포함
A04가동률과 분모해결사용자가 날짜 행마다 라인당 20시간을 지정. 월별 실제 합계 ÷ 월별 계획 합계. 보전일 포함.
근거와 후보
파일 근거
  • daily_report.xlsx 3월!C9
후보 답변
  • 하루 24시간
  • 라인별 계획 가동시간
영향 범위
  • 월 가동률
A04b생산량과 단위해결사용자가 t에 1,000을 곱해 kg으로 합산하고 일별 추이와 월별 합계를 표시하도록 확인.
근거와 후보
파일 근거
  • daily_report.xlsx 3월!B6:B7
후보 답변
  • kg
  • t
영향 범위
  • 생산량
A05시간 기준해결사용자가 날짜 행을 이용해 일별과 월별 집계를 지정. 원본 제목의 연도는 2025년.
근거와 후보
파일 근거
  • daily_report.xlsx 3월!A1:F31, 4월!A1:F32
후보 답변
  • 일보의 일자 및 해당 월
A06정기 보전일 가동시간해결사용자가 두 보전일 모두 실제 가동 0시간으로 확인.
근거와 후보
파일 근거
  • daily_report.xlsx 3월!E14
  • daily_report.xlsx 4월!C12
후보 답변
  • 0시간
  • 미기록
영향 범위
  • 월 가동률
A07정기 보전일 생산량해결사용자가 두 생산량 모두 해당 없음으로 확인. 빈 생산량과 상태 열로 기록하고 합계에서 제외.
근거와 후보
파일 근거
  • daily_report.xlsx 3월!D14
  • daily_report.xlsx 4월!B12
후보 답변
  • 0 kg
  • 해당 없음
영향 범위
  • 일별 생산량
  • 생산량 관측 건수
A08조인 키해당 없음같은 구조인 월별 시트를 행 방향으로 연결했으며 외부 표와의 조인은 없음.
근거와 후보
파일 근거
  • daily_report.xlsx 3월!A1:F31, 4월!A1:F32

데이터 개요

데이터 세트
  • ID
    3월
    형식
    xlsx
    행 수
    21
    열 수
    6
    읽은 범위
    • daily_report.xlsx 3월!A1:F31 전체, 머리글 4~5행, 병합 B4:C4 및 D4:E4
  • ID
    4월
    형식
    xlsx
    행 수
    22
    열 수
    6
    읽은 범위
    • daily_report.xlsx 4월!A1:F32 전체, 머리글 4~5행, 병합 B4:C4 및 D4:E4
행 단위
한 행은 기록 날짜 하나이며 A·B 두 라인을 포함합니다. ZIP 안의 Excel 통합 문서 구조가 .xlsx 확장자와 일치합니다. 두 시트의 사용 범위를 모두 읽었습니다.

지표

지표값정의분자분모조건근거 위치
3월 A라인 생산량258,340 kg21개 날짜 행에 기록된 생산량 합계. t는 1,000을 곱해 kg으로 환산. 합계 지표에는 분자와 분모가 적용되지 않음.
  • daily_report.xlsx 3월!B6:B10, B12:B16, B18:B22, B24:B28, B30
3월 A라인 가동률93.81 %실제 가동시간 394시간 ÷ 계획 가동시간 420시간 × 100. 계획은 날짜 행 21개 × 20시간이며 보전일 포함.394420
  • daily_report.xlsx 3월!C6:C10, C12:C16, C18:C22, C24:C28, C30
  • daily_report.xlsx 3월!A6:A10, A12:A16, A18:A22, A24:A28, A30
3월 B라인 생산량211,400 kg20개 날짜 행에 기록된 생산량 합계. t는 1,000을 곱해 kg으로 환산. 합계 지표에는 분자와 분모가 적용되지 않음.
  • daily_report.xlsx 3월!D6:D10, D12:D13, D15:D16, D18:D22, D24:D28, D30
3월 B라인 가동률81.43 %실제 가동시간 342시간 ÷ 계획 가동시간 420시간 × 100. 계획은 날짜 행 21개 × 20시간이며 보전일 포함.342420
  • daily_report.xlsx 3월!E6:E10, E12:E16, E18:E22, E24:E28, E30
  • daily_report.xlsx 3월!A6:A10, A12:A16, A18:A22, A24:A28, A30
4월 A라인 생산량264,160 kg21개 날짜 행에 기록된 생산량 합계. t는 1,000을 곱해 kg으로 환산. 합계 지표에는 분자와 분모가 적용되지 않음.
  • daily_report.xlsx 4월!B6:B9, B11, B13:B15, B17:B21, B23:B27, B29:B31
4월 A라인 가동률89.55 %실제 가동시간 394시간 ÷ 계획 가동시간 440시간 × 100. 계획은 날짜 행 22개 × 20시간이며 보전일 포함.394440
  • daily_report.xlsx 4월!C6:C9, C11:C15, C17:C21, C23:C27, C29:C31
  • daily_report.xlsx 4월!A6:A9, A11:A15, A17:A21, A23:A27, A29:A31
4월 B라인 생산량237,700 kg22개 날짜 행에 기록된 생산량 합계. t는 1,000을 곱해 kg으로 환산. 합계 지표에는 분자와 분모가 적용되지 않음.
  • daily_report.xlsx 4월!D6:D9, D11:D15, D17:D21, D23:D27, D29:D31
4월 B라인 가동률86.14 %실제 가동시간 379시간 ÷ 계획 가동시간 440시간 × 100. 계획은 날짜 행 22개 × 20시간이며 보전일 포함.379440
  • daily_report.xlsx 4월!E6:E9, E11:E15, E17:E21, E23:E27, E29:E31
  • daily_report.xlsx 4월!A6:A9, A11:A15, A17:A21, A23:A27, A29:A31

재현 절차

필터
  • 3월·4월 시트의 A열에서 ‘월 일(요일)’ 패턴에 맞는 행을 선택했습니다.
  • 라인별 생산량 합계에는 숫자로 기록된 생산량을 사용했습니다. 월 가동률은 같은 월의 날짜 행 전체를 사용했습니다.
제외 내역
  • 적용 범위
    모든 지표
    근거 위치
    • daily_report.xlsx 3월 시트 1, 2, 3, 4, 5행
    사유
    일자 없음 (제목·결재·빈 행·머리글)
  • 적용 범위
    모든 지표
    근거 위치
    • daily_report.xlsx 3월 시트 11, 17, 23, 29행
    사유
    주간 소계
  • 적용 범위
    모든 지표
    근거 위치
    • daily_report.xlsx 3월 시트 31행
    사유
    월 합계
  • 적용 범위
    모든 지표
    근거 위치
    • daily_report.xlsx 4월 시트 1, 2, 3, 4, 5행
    사유
    일자 없음 (제목·결재·빈 행·머리글)
  • 적용 범위
    모든 지표
    근거 위치
    • daily_report.xlsx 4월 시트 10, 16, 22, 28행
    사유
    주간 소계
  • 적용 범위
    모든 지표
    근거 위치
    • daily_report.xlsx 4월 시트 32행
    사유
    월 합계
  • 적용 범위
    생산량만
    근거 위치
    • daily_report.xlsx 3월!D14
    • daily_report.xlsx 4월!B12
    사유
    정기 보전일 생산량 해당 없음
변환 단계
  • 입력
    daily_report.xlsx
    변환
    두 시트의 물리적 셀 범위를 읽음
    결과
    원본 행
    변환 전
    63
    변환 후
    63
  • 입력
    원본 행
    변환
    날짜 행 선택, 단위를 kg으로 통일, 보전일 처리
    결과
    정리 CSV
    변환 전
    63
    변환 후
    43
  • 입력
    정리 CSV
    변환
    날짜 행 범위와 실제·계획 가동시간을 공유하는 월·라인별 집계
    결과
    월·라인 집계
    변환 전
    43
    변환 후
    4
표본 크기
원본 행
63
날짜 행
43
3월 날짜 행
21
4월 날짜 행
22
라인별 생산량 관측
84
라인별 가동시간 관측
86
월·라인 집계
4
원본 위치
  • daily_report.xlsx 3월!A1:F31, 4월!A1:F32
  • daily_report.xlsx 3월!B17 및 B12:B16
  • delivery/cleaned_daily_report.csv의 _source_sheet, _source_row
  • delivery/excluded.csv

재현 코드

작업 디렉터리 eda-work

python3 -I delivery/clean.py ../daily_report.xlsx delivery/cleaned_daily_report.csv excluded.csv
python3 -I ../eda-skill/scripts/audit_clean.py ../daily_report.xlsx --cleaned delivery/cleaned_daily_report.csv --excluded excluded.csv --header-row 0 --sheets 3월,4월
MPLCONFIGDIR=.matplotlib python3 -I analyze.py
python3 -I ../eda-skill/scripts/build_report.py --spec report-spec.json --outdir delivery

import json
import re
from pathlib import Path

import matplotlib as mpl
mpl.use("Agg")
import matplotlib.pyplot as plt
from matplotlib import dates as mdates, font_manager, ticker
import pandas as pd


delivery = Path("delivery")
daily = pd.read_csv(delivery / "cleaned_daily_report.csv", parse_dates=["일자"])
excluded = pd.read_csv("excluded.csv")
source = "daily_report.xlsx"
lines = ("A라인", "B라인")
months = ("3월", "4월")
colors = ("#17665f", "#a54a24")
hours_per_day = 20
assert len(daily) + len(excluded) == 63
assert not daily.duplicated().any()
assert daily["일자"].is_unique
assert not daily[["_source_sheet", "_source_row"]].duplicated().any()

font_path = Path("AppleGothic.ttf")  # 시스템 설치 경로로 지정
if font_path.is_file():
    font_manager.fontManager.addfont(font_path)
    mpl.rcParams["font.family"] = font_manager.FontProperties(fname=font_path).get_name()
mpl.rcParams.update({
    "axes.spines.top": False, "axes.spines.right": False,
    "axes.labelcolor": "#273742", "axes.titlecolor": "#12252c", "text.color": "#12252c",
    "xtick.color": "#273742", "ytick.color": "#273742",
    "axes.unicode_minus": False, "savefig.dpi": 160,
})


def source_ref(sheet, rows, columns):
    groups = []
    start = end = rows[0]
    for row in rows[1:]:
        if row == end + 1:
            end = row
        else:
            groups.append((start, end))
            start = end = row
    groups.append((start, end))
    ranges = [f"{columns}{lo}" if lo == hi else f"{columns}{lo}:{columns}{hi}" for lo, hi in groups]
    return f"{source} {sheet}!{', '.join(ranges)}"


def create_figure():
    fig, ax = plt.subplots(figsize=(9.4, 3.7), layout="constrained")
    ax.set_axisbelow(True)
    ax.grid(axis="y", color="#e1e8ec")
    return fig, ax


def save(fig, chart_id):
    fig.savefig(delivery / "figures" / f"{chart_id}.png", facecolor="white")
    plt.close(fig)


def chart(chart_id, kind, question, columns, used, omitted, reason, observation, caption):
    return {
        "id": chart_id, "image_path": f"delivery/figures/{chart_id}.png", "type": kind,
        "question": question, "source_columns": columns, "n_used": int(used), "n_excluded": int(omitted),
        "exclusion_reason": reason, "observation": observation, "domain_interpretation": caption,
    }


metrics = []
monthly = {}
rates = {}
production = {}
for sheet, frame in daily.groupby("_source_sheet", sort=False):
    assert frame["일자"].dt.month.eq(int(sheet[0])).all()
    monthly[sheet] = len(frame)
    for line, mass_letter, hours_letter in zip(lines, ("B", "D"), ("C", "E")):
        mass_column, hours_column = f"{line} 생산량", f"{line} 가동시간"
        assert frame[hours_column].between(0, hours_per_day).all()
        assert frame[mass_column].isna().equals(frame[f"{line} 생산량 상태"].eq("해당 없음"))
        mass_rows = frame.loc[frame[mass_column].notna(), "_source_row"].tolist()
        all_rows = frame["_source_row"].tolist()
        mass = int(frame[mass_column].sum(min_count=1))
        hours = int(frame[hours_column].sum())
        plan = len(all_rows) * hours_per_day
        production[sheet, line] = mass
        rates[sheet, line] = hours / plan * 100
        metrics += [
            dict(name=f"{sheet} {line} 생산량", definition=f"{len(mass_rows)}개 날짜 행에 기록된 생산량 합계. t는 1,000을 곱해 kg으로 환산. 합계 지표에는 분자와 분모가 적용되지 않음.",
                 numerator=None, denominator=None, value=mass, unit="kg", depends_on_ambiguity_ids=[],
                 condition=None, source_refs=[source_ref(sheet, mass_rows, mass_letter)]),
            dict(name=f"{sheet} {line} 가동률", definition=f"실제 가동시간 {hours}시간 ÷ 계획 가동시간 {plan}시간 × 100. 계획은 날짜 행 {len(all_rows)}개 × 20시간이며 보전일 포함.",
                 numerator=hours, denominator=plan, value=rates[sheet, line], unit="%", depends_on_ambiguity_ids=[],
                 condition=None, source_refs=[source_ref(sheet, all_rows, hours_letter), source_ref(sheet, all_rows, "A")]),
        ]

mass_columns = [f"{line} 생산량" for line in lines]
hours_columns = [f"{line} 가동시간" for line in lines]
mass_n = int(daily[mass_columns].count().sum())
mass_missing = int(daily[mass_columns].isna().sum().sum())
total_line_days = len(lines) * len(daily)
missing_dates = pd.date_range(daily["일자"].min(), daily["일자"].max()).difference(daily["일자"])
assert len(missing_dates) == 16 and all(missing_dates.day_of_week >= 5)

charts = []
for chart_id, values, label, unit, limit, fmt, observation, caption, used, omitted in (
    ("monthly_production", production, "월 생산량", "kg", 305000, "{:,.0f}",
     f"daily_report.xlsx 3월·4월 시트 날짜 행 {len(daily)}개에서 {mass_n}개 생산량을 합산해 월·라인별 막대 4개를 표시했습니다. 보전일 생산량 {mass_missing}건은 해당 없음으로 합산에서 제외했습니다.",
     "두 라인 모두 4월에 월 생산량이 늘었습니다.", mass_n, mass_missing),
    ("monthly_utilization", rates, "월 가동률", "%", 110, "{:.2f}%",
     f"daily_report.xlsx 3월·4월 시트 날짜 행 {len(daily)}개에 기록된 라인별 가동시간 {total_line_days}건을 사용해 월·라인별 막대 4개를 표시했습니다. 제외 0건이며 보전일 0시간을 포함합니다.",
     "3월에서 4월 사이 A라인 가동률은 하락했고 B라인 가동률은 상승했습니다.", total_line_days, 0),
):
    fig, ax = create_figure()
    for i, line in enumerate(lines):
        x = [j + (i - .5) * .32 for j in range(len(months))]
        y = [values[m, line] for m in months]
        bars = ax.bar(x, y, width=.29, label=line, color=colors[i])
        ax.bar_label(bars, [fmt.format(v) for v in y], padding=4)
    ax.set(xticks=range(len(months)), xticklabels=months, ylim=(0, limit), ylabel=f"{label} ({unit})")
    ax.yaxis.set_major_formatter(ticker.StrMethodFormatter("{x:,.0f}"))
    ax.legend(frameon=False, loc="upper center", bbox_to_anchor=(.5, 1.14), ncol=2)
    save(fig, chart_id)
    columns = mass_columns if chart_id == "monthly_production" else hours_columns
    reason = "정기 보전일 생산량 해당 없음" if omitted else None
    charts.append(chart(chart_id, "grouped_bar", f"3월과 4월의 라인별 {label}은 어떻게 달라졌나요?",
                        ["일자", *columns], used, omitted, reason, observation, caption))

fig, ax = create_figure()
grid = pd.date_range(daily["일자"].min(), daily["일자"].max())
series = daily.set_index("일자").reindex(grid)
for i, line in enumerate(lines):
    ax.plot(grid, series[f"{line} 생산량"], marker="o", markersize=3.7, linewidth=1.6, label=line, color=colors[i])
for stamp, text in (("2025-03-12", "B라인 보전"), ("2025-04-08", "A라인 보전")):
    when = pd.Timestamp(stamp)
    ax.axvline(when, linewidth=1, linestyle=":", color="#687980")
    ax.annotate(text, (when, 13150), xytext=(0, 3), textcoords="offset points", ha="center", fontsize=8)
ax.set(xlabel="일자 (2025년)", ylabel="일 생산량 (kg)", ylim=(9700, 13600))
ax.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=mdates.MO))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%m/%d"))
ax.yaxis.set_major_formatter(ticker.StrMethodFormatter("{x:,.0f}"))
ax.legend(frameon=False, loc="upper center", bbox_to_anchor=(.5, 1.14), ncol=2)
save(fig, "daily_production")
charts.append(chart(
    "daily_production", "line_time", "각 라인의 일 생산량은 어떻게 움직였나요?", ["일자", *mass_columns],
    mass_n, mass_missing, "정기 보전일 생산량 해당 없음",
    f"daily_report.xlsx 3월·4월 시트 일자 행 {len(daily)}개의 라인별 생산량 {mass_n}건(kg)을 표시했습니다. 보전일 {mass_missing}건과 일보에 없는 주말 {len(missing_dates)}일은 그래프가 끊깁니다.",
    "기록된 일 생산량 범위는 A라인 11,860~12,900 kg, B라인 10,200~11,100 kg입니다.",
))
assert [(int(daily[c].min()), int(daily[c].max())) for c in mass_columns] == [(11860, 12900), (10200, 11100)]

a_delta = production["4월", "A라인"] - production["3월", "A라인"]
b_delta = production["4월", "B라인"] - production["3월", "B라인"]
a_pp = rates["4월", "A라인"] - rates["3월", "A라인"]
b_pp = rates["4월", "B라인"] - rates["3월", "B라인"]


def item(id_, label, evidence, candidates, answer, affects, question=None, status="resolved"):
    return dict(id=id_, checklist_item=label, question=question, file_evidence=evidence,
                candidates=candidates, answer=answer, affects=affects, status=status)


both = f"{source} 3월!A1:F31, 4월!A1:F32"
exception_mass = [f"{source} 3월!D14", f"{source} 4월!B12"]
exception_hours = [f"{source} 3월!E14", f"{source} 4월!C12"]
log = [
    item("A01", "업무 과정", [both], [], "사용자 설명과 시트 제목에서 생산 현장 일보임을 확인.", []),
    item("A02", "분석 목적과 활용", [both], ["월간 실적 공유", "생산계획 조정", "설비 보전 검토"],
         "라인별 추이 비교 요청. 활용처는 사용자 답변 ‘모르겠어요’로 미정.",
         ["결과 활용처"], "라인별 월 생산량과 가동률을 비교한 결과를 어디에 쓰실 예정인가요?", "unresolved"),
    item("A03", "행과 머리글", [f"{source} 3월·4월!A4:F5"], ["날짜 행", "소계·합계 포함"],
         "사용자가 날짜가 있는 행을 지정. 원본 4행은 그룹명과 일자·비고, 5행은 라인별 필드명. 날짜 한 행에 두 라인 기록.", []),
    item("A04", "가동률과 분모", [f"{source} 3월!C9"],
         ["하루 24시간", "라인별 계획 가동시간"], "사용자가 날짜 행마다 라인당 20시간을 지정. 월별 실제 합계 ÷ 월별 계획 합계. 보전일 포함.",
         ["월 가동률"]),
    item("A04b", "생산량과 단위", [f"{source} 3월!B6:B7"], ["kg", "t"],
         "사용자가 t에 1,000을 곱해 kg으로 합산하고 일별 추이와 월별 합계를 표시하도록 확인.", ["생산량"]),
    item("A05", "시간 기준", [both], ["일보의 일자 및 해당 월"], "사용자가 날짜 행을 이용해 일별과 월별 집계를 지정. 원본 제목의 연도는 2025년.", []),
    item("A06", "정기 보전일 가동시간", exception_hours, ["0시간", "미기록"],
         "사용자가 두 보전일 모두 실제 가동 0시간으로 확인.", ["월 가동률"]),
    item("A07", "정기 보전일 생산량", exception_mass, ["0 kg", "해당 없음"],
         "사용자가 두 생산량 모두 해당 없음으로 확인. 빈 생산량과 상태 열로 기록하고 합계에서 제외.", ["일별 생산량", "생산량 관측 건수"]),
    item("A08", "조인 키", [both], [], "같은 구조인 월별 시트를 행 방향으로 연결했으며 외부 표와의 조인은 없음.", [], status="not_applicable"),
]

datasets = []
exclusions = []
header_names = ["일자", "A라인 / 생산량", "A라인 / 가동시간", "B라인 / 생산량", "B라인 / 가동시간", "비고"]
for sheet, last in zip(months, (31, 32)):
    datasets.append(dict(id=f"sheet:{sheet}", format="xlsx", rows=monthly[sheet], columns=6, unread=[],
                         read_ranges=[f"{source} {sheet}!A1:F{last} 전체, 머리글 4~5행, 병합 B4:C4 및 D4:E4"],
                         structure=dict(sheet=sheet, header_rows=[4, 5], record_path=f"A6:F{last}", column_names=header_names)))
    for reason, rows in excluded.loc[excluded["_source_sheet"].eq(sheet)].groupby("reason", sort=False):
        exclusions.append(dict(scope="모든 지표", source_refs=[f"{source} {sheet} 시트 " + ", ".join(map(str, rows["_source_row"])) + "행"], reason=reason))
exclusions.append(dict(scope="생산량만", source_refs=exception_mass, reason="정기 보전일 생산량 해당 없음"))

analysis_code = Path("analyze.py").read_text()
report = dict(
    title="A·B라인 생산 일보 | 2025년 3–4월",
    language="ko",
    headline=f"3월에서 4월 사이 A라인 월 생산량은 {a_delta:,} kg 늘고 가동률은 {abs(a_pp):.2f}%p 하락했습니다. B라인은 {b_delta:,} kg, {b_pp:.2f}%p 올랐습니다. daily_report.xlsx의 3월·4월 날짜 행 기준입니다.",
    kpis=[f"4월 {line} {measure}" for line in lines for measure in ("생산량", "가동률")],
    key_charts=["monthly_production", "monthly_utilization"],
    insights=[
        dict(text="두 달 모두 A라인 생산량이 B라인을 앞섰고, 4월 격차는 26,460 kg이었습니다.", source=f"{source} 4월 시트 B·D열 날짜 행"),
        dict(text="4월 계획 가동시간은 440시간으로 3월보다 라인당 20시간 늘었고, A라인 실제 가동시간은 두 달 모두 394시간이었습니다.", source=f"{source} 3월·4월 시트 A·C열 날짜 행"),
    ],
    charts=charts,
    metrics=metrics,
    ambiguity_log=log,
    data_overview=dict(datasets=datasets, row_grain="한 행은 기록 날짜 하나이며 A·B 두 라인을 포함합니다. ZIP 안의 Excel 통합 문서 구조가 .xlsx 확장자와 일치합니다. 두 시트의 사용 범위를 모두 읽었습니다."),
    assumptions_limitations=[
        f"날짜 행 {len(daily)}개에 중복 날짜나 빈 일자·생산량·가동시간 원본 셀이 없었습니다. 생산량 단위는 kg와 t였고, 업무상 해당 없음 2건 외 날짜·수치 파싱 실패는 0건입니다. 가동시간은 보전일 0시간을 포함해 0~20시간입니다. 비고가 빈 날짜 행은 {daily['비고'].isna().sum()}개입니다.",
        f"{source} 3월!B17 주간 소계는 62,500 kg이며, B12:B16 날짜 행의 합계는 61,500 kg입니다. 차이 1,000 kg. 두 시트의 월 합계는 날짜 행 집계와 일치합니다.",
        f"기록 기간 중 날짜 행이 없는 {len(missing_dates)}일은 모두 주말입니다. 이 날짜는 계획 가동시간에 포함하지 않았습니다. 날짜 행이 있는 보전일은 포함했습니다.",
        "결과의 업무 활용처는 미정입니다. 월별 지표에는 기간 중 날짜 행 수 차이가 반영됩니다.",
        "분포도와 상관관계 그림은 생략했습니다. 일별 그림은 원래 날짜 순서를 보여주며, 요청한 비교는 월별 막대 그림에서 확인할 수 있습니다.",
    ],
    reproducibility=dict(
        filters=["3월·4월 시트의 A열에서 ‘월 일(요일)’ 패턴에 맞는 행을 선택했습니다.", "라인별 생산량 합계에는 숫자로 기록된 생산량을 사용했습니다. 월 가동률은 같은 월의 날짜 행 전체를 사용했습니다."],
        exclusions=exclusions,
        transforms=[
            dict(input=source, transform="두 시트의 물리적 셀 범위를 읽음", output="원본 행", before=63, after=63),
            dict(input="원본 행", transform="날짜 행 선택, 단위를 kg으로 통일, 보전일 처리", output="정리 CSV", before=63, after=len(daily)),
            dict(input="정리 CSV", transform="날짜 행 범위와 실제·계획 가동시간을 공유하는 월·라인별 집계", output="월·라인 집계", before=len(daily), after=len(rates)),
        ],
        sample_sizes={"원본 행": 63, "날짜 행": len(daily), "3월 날짜 행": monthly["3월"], "4월 날짜 행": monthly["4월"],
                      "라인별 생산량 관측": mass_n, "라인별 가동시간 관측": total_line_days, "월·라인 집계": len(rates)},
        source_locators=[both, f"{source} 3월!B17 및 B12:B16", "delivery/cleaned_daily_report.csv의 _source_sheet, _source_row", "delivery/excluded.csv"],
        code="작업 디렉터리 eda-work\n\n"
             "python3 -I delivery/clean.py ../daily_report.xlsx delivery/cleaned_daily_report.csv excluded.csv\n"
             "python3 -I ../eda-skill/scripts/audit_clean.py ../daily_report.xlsx --cleaned delivery/cleaned_daily_report.csv --excluded excluded.csv --header-row 0 --sheets 3월,4월\n"
             "MPLCONFIGDIR=.matplotlib python3 -I analyze.py\n"
             "python3 -I ../eda-skill/scripts/build_report.py --spec report-spec.json --outdir delivery\n\n"
             + re.sub(r'^font_path = Path\(.+\)$', 'font_path = Path("AppleGothic.ttf")  # 시스템 설치 경로로 지정', analysis_code, flags=re.M),
    ),
)
assert production["4월", "A라인"] - production["4월", "B라인"] == 26460
assert [m["numerator"] for m in metrics if m["unit"] == "%"] == [394, 342, 394, 379]
Path("report-spec.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps({"production": list(production.values()), "rates": list(rates.values()),
                  "changes": [a_delta, b_delta, a_pp, b_pp]}, ensure_ascii=False))