output.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import os
  2. import csv
  3. from datetime import datetime
  4. from iepy.data.models import EvidenceLabel
  5. def dump_runner_output_to_csv(results, filepath):
  6. """
  7. Takes the result of a runner and dumps it into a csv file with the
  8. following format:
  9. <candidate_evidence_id>,<relation_is_present_boolean>
  10. """
  11. if os.path.exists(filepath):
  12. raise ValueError("Output file path already exists")
  13. with open(filepath, "w", newline='') as filehandler:
  14. csv_writer = csv.writer(filehandler)
  15. csv_writer.writerow(["Candidate evidence id", "Relation present"])
  16. for prediction, value in results.items():
  17. prediction_id = prediction.id
  18. csv_writer.writerow([prediction_id, value])
  19. def dump_predictions_to_database(relation, predictions):
  20. judge = "iepy-run on {}".format(datetime.now().strftime("%Y-%m-%d %H:%M"))
  21. for evidence, relation_is_present in predictions.items():
  22. label = EvidenceLabel.YESRELATION if relation_is_present else EvidenceLabel.NORELATION
  23. evidence.set_label(relation, label, judge, labeled_by_machine=True)
  24. def dump_output_loop(predictions):
  25. """
  26. Ask the user the filepat to store the runner's result.
  27. If the file already exists keeps asking until it gets an answer
  28. """
  29. while True:
  30. output_filepath = input("\nChoose the filename of the output (in csv format): ")
  31. try:
  32. dump_runner_output_to_csv(predictions, output_filepath)
  33. break
  34. except ValueError:
  35. print("Error: file already exists, try another one.\n")
  36. except FileNotFoundError:
  37. print("Error: couldn't open the file, try another one.\n")
  38. def dump_classifier_loop(extractor):
  39. """
  40. Ask the user if he wants to save the classifier, and in that case where.
  41. If the file already exists keeps asking until it gets an answer
  42. """
  43. while True:
  44. answer = input("\nDo you want to save the classifier generated? (y/n): ")
  45. if answer not in ["y", "n", "yes", "no"]:
  46. print("Invalid answer\n")
  47. else:
  48. break
  49. if answer in ["y", "yes"]:
  50. while True:
  51. output_filepath = input("\nChoose the filename of the output: ")
  52. try:
  53. extractor.save(output_filepath)
  54. break
  55. except ValueError:
  56. print("Error: file already exists, try another one.\n")
  57. except FileNotFoundError:
  58. print("Error: couldn't open the file, try another one.\n")