benchmark_lighthouse.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. """Extracts the Lighthouse scores from the JSON files in the specified directory and inserts them into the database."""
  2. from __future__ import annotations
  3. import json
  4. import os
  5. import sys
  6. from utils import send_data_to_posthog
  7. def insert_benchmarking_data(
  8. lighthouse_data: dict,
  9. commit_sha: str,
  10. ):
  11. """Insert the benchmarking data into the database.
  12. Args:
  13. lighthouse_data: The Lighthouse data to insert.
  14. commit_sha: The commit SHA to insert.
  15. """
  16. properties = {
  17. "distinct_id": commit_sha,
  18. "lighthouse_data": lighthouse_data,
  19. }
  20. # Send the data to PostHog
  21. send_data_to_posthog("lighthouse_benchmark", properties)
  22. def get_lighthouse_scores(directory_path: str) -> dict:
  23. """Extracts the Lighthouse scores from the JSON files in the specified directory.
  24. Args:
  25. directory_path (str): The path to the directory containing the JSON files.
  26. Returns:
  27. dict: The Lighthouse scores.
  28. """
  29. scores = {}
  30. try:
  31. for filename in os.listdir(directory_path):
  32. if filename.endswith(".json") and filename != "manifest.json":
  33. file_path = os.path.join(directory_path, filename)
  34. with open(file_path, "r") as file:
  35. data = json.load(file)
  36. # Extract scores and add them to the dictionary with the filename as key
  37. scores[data["finalUrl"].replace("http://localhost:3000/", "/")] = {
  38. "performance_score": data["categories"]["performance"]["score"],
  39. "accessibility_score": data["categories"]["accessibility"][
  40. "score"
  41. ],
  42. "best_practices_score": data["categories"]["best-practices"][
  43. "score"
  44. ],
  45. "seo_score": data["categories"]["seo"]["score"],
  46. }
  47. except Exception as e:
  48. return {"error": e}
  49. return scores
  50. def main():
  51. """Runs the benchmarks and inserts the results into the database."""
  52. # Get the commit SHA and JSON directory from the command line arguments
  53. commit_sha = sys.argv[1]
  54. json_dir = sys.argv[2]
  55. # Get the Lighthouse scores
  56. lighthouse_scores = get_lighthouse_scores(json_dir)
  57. # Insert the data into the database
  58. insert_benchmarking_data(lighthouse_scores, commit_sha)
  59. if __name__ == "__main__":
  60. main()