grade.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import csv
  2. import os
  3. import shutil
  4. import subprocess
  5. import sys
  6. import tempfile
  7. from decimal import Decimal, InvalidOperation
  8. SCRIPT = "/app/summarize.py"
  9. TASK_INPUT = "/tests/task_input.csv"
  10. TEST_INPUT = "/tests/input.csv"
  11. SUMMARY = "/app/summary.csv"
  12. FILTERED = "/app/over_500.csv"
  13. DETAIL_HEADER = ["日期", "姓名", "类别", "金额"]
  14. SUMMARY_HEADER = ["姓名", "报销总额"]
  15. def read_csv(path):
  16. with open(path, encoding="utf-8-sig", newline="") as stream:
  17. return list(csv.reader(stream))
  18. def fail(message):
  19. os.makedirs("/logs/verifier", exist_ok=True)
  20. with open("/logs/verifier/reward.txt", "w", encoding="utf-8") as reward:
  21. reward.write("0\n")
  22. print(message)
  23. raise SystemExit(0)
  24. def expected_rows(source):
  25. if not source or source[0] != DETAIL_HEADER:
  26. raise ValueError("invalid verifier input")
  27. totals = {}
  28. order = []
  29. filtered = []
  30. for row in source[1:]:
  31. if len(row) != 4:
  32. raise ValueError("invalid verifier input")
  33. _, name, _, raw_amount = row
  34. amount = Decimal(raw_amount)
  35. if name not in totals:
  36. totals[name] = Decimal("0")
  37. order.append(name)
  38. totals[name] += amount
  39. if amount > Decimal("500"):
  40. filtered.append(row)
  41. summary = [SUMMARY_HEADER]
  42. summary.extend([[name, f"{totals[name]:.2f}"] for name in order])
  43. return summary, [DETAIL_HEADER, *filtered]
  44. def check_outputs(input_path, summary_path, filtered_path):
  45. source = read_csv(input_path)
  46. summary, filtered = expected_rows(source)
  47. return outputs_match(summary_path, filtered_path, summary, filtered)
  48. def outputs_match(summary_path, filtered_path, summary, filtered):
  49. if read_csv(summary_path) != summary or read_csv(filtered_path) != filtered:
  50. return False
  51. return True
  52. def main():
  53. try:
  54. if not os.path.isfile(SCRIPT):
  55. fail("Required summary program is missing.")
  56. if not check_outputs(TASK_INPUT, SUMMARY, FILTERED):
  57. fail("Outputs for the provided CSV do not match the task requirements.")
  58. test_source = read_csv(TEST_INPUT)
  59. expected_summary, expected_filtered = expected_rows(test_source)
  60. with tempfile.TemporaryDirectory(prefix="expense-summary-") as temp_dir:
  61. staged_input = os.path.join(temp_dir, "input.csv")
  62. summary_path = os.path.join(temp_dir, "summary.csv")
  63. filtered_path = os.path.join(temp_dir, "over_500.csv")
  64. shutil.copyfile(TEST_INPUT, staged_input)
  65. try:
  66. subprocess.run(
  67. [sys.executable, SCRIPT, staged_input, summary_path, filtered_path],
  68. check=True,
  69. timeout=20,
  70. stdout=subprocess.DEVNULL,
  71. stderr=subprocess.DEVNULL,
  72. )
  73. except (OSError, subprocess.SubprocessError):
  74. fail("Summary program could not process the verifier CSV.")
  75. if not outputs_match(
  76. summary_path, filtered_path, expected_summary, expected_filtered
  77. ):
  78. fail("Summary program output does not meet the task requirements.")
  79. except (OSError, csv.Error, InvalidOperation, ValueError, KeyError):
  80. fail("Required CSV files are missing, unreadable, or invalid.")
  81. os.makedirs("/logs/verifier", exist_ok=True)
  82. with open("/logs/verifier/reward.txt", "w", encoding="utf-8") as reward:
  83. reward.write("1\n")
  84. print("Outputs meet the task requirements.")
  85. if __name__ == "__main__":
  86. main()