task.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import re
  2. import math
  3. from datetime import datetime
  4. from typing import Optional
  5. def prompt_template(
  6. template: str, user_name: str = None, current_location: str = None
  7. ) -> str:
  8. # Get the current date
  9. current_date = datetime.now()
  10. # Format the date to YYYY-MM-DD
  11. formatted_date = current_date.strftime("%Y-%m-%d")
  12. # Replace {{CURRENT_DATE}} in the template with the formatted date
  13. template = template.replace("{{CURRENT_DATE}}", formatted_date)
  14. if user_name:
  15. # Replace {{USER_NAME}} in the template with the user's name
  16. template = template.replace("{{USER_NAME}}", user_name)
  17. if current_location:
  18. # Replace {{CURRENT_LOCATION}} in the template with the current location
  19. template = template.replace("{{CURRENT_LOCATION}}", current_location)
  20. return template
  21. def title_generation_template(
  22. template: str, prompt: str, user: Optional[dict] = None
  23. ) -> str:
  24. def replacement_function(match):
  25. full_match = match.group(0)
  26. start_length = match.group(1)
  27. end_length = match.group(2)
  28. middle_length = match.group(3)
  29. if full_match == "{{prompt}}":
  30. return prompt
  31. elif start_length is not None:
  32. return prompt[: int(start_length)]
  33. elif end_length is not None:
  34. return prompt[-int(end_length) :]
  35. elif middle_length is not None:
  36. middle_length = int(middle_length)
  37. if len(prompt) <= middle_length:
  38. return prompt
  39. start = prompt[: math.ceil(middle_length / 2)]
  40. end = prompt[-math.floor(middle_length / 2) :]
  41. return f"{start}...{end}"
  42. return ""
  43. template = re.sub(
  44. r"{{prompt}}|{{prompt:start:(\d+)}}|{{prompt:end:(\d+)}}|{{prompt:middletruncate:(\d+)}}",
  45. replacement_function,
  46. template,
  47. )
  48. template = prompt_template(
  49. template,
  50. **(
  51. {"user_name": user.get("name"), "current_location": user.get("location")}
  52. if user
  53. else {}
  54. ),
  55. )
  56. return template