result.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import click
  2. import flask
  3. from flask.cli import AppGroup
  4. from pycs import app
  5. from pycs.database.Project import Project
  6. result_cli = AppGroup("result", short_help="Result operations")
  7. @result_cli.command("export")
  8. @click.argument("project_id")
  9. @click.argument("indent", required=False)
  10. @click.argument("output", required=False)
  11. def export(project_id, output, indent):
  12. """ Export results for a specific project or for all projects """
  13. if project_id == "all":
  14. projects = Project.query.all()
  15. app.logger.info(f"Exporting results for all projects ({len(projects)})!")
  16. if output is None:
  17. output = "output.json"
  18. else:
  19. project = Project.query.get(project_id)
  20. if project is None:
  21. app.logger.error(f"Could not find project with ID {project_id}!")
  22. return
  23. app.logger.info(f"Exporting results for project {project}!")
  24. projects = [project]
  25. if output is None:
  26. output = f"output_project_{int(project_id):04d}.json"
  27. app.logger.info(f"Exporting to {output}")
  28. results = []
  29. for project in projects:
  30. project_files = [
  31. dict(**f.serialize(),
  32. results=[
  33. dict(**r.serialize(), label=r.label.serialize() if r.label is not None else None)
  34. for r in f.results.all()
  35. ])
  36. for f in project.files.all() if f.results.count() != 0
  37. ]
  38. results.append(dict(
  39. project_id=project.id,
  40. files=project_files,
  41. labels=[lab.serialize() for lab in project.labels.all()],
  42. ))
  43. if indent is not None:
  44. indent = int(indent)
  45. with open(output, "w", encoding="utf-8") as out_f:
  46. flask.json.dump(results, out_f, app=app, indent=indent)