ChatterBot 1.2.16__tar.gz → 1.2.18__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. {chatterbot-1.2.16 → chatterbot-1.2.18}/ChatterBot.egg-info/PKG-INFO +7 -7
  2. {chatterbot-1.2.16 → chatterbot-1.2.18}/ChatterBot.egg-info/SOURCES.txt +1 -0
  3. {chatterbot-1.2.16 → chatterbot-1.2.18}/ChatterBot.egg-info/requires.txt +6 -6
  4. {chatterbot-1.2.16 → chatterbot-1.2.18}/PKG-INFO +7 -7
  5. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/__init__.py +1 -1
  6. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/chatterbot.py +24 -5
  7. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/comparisons.py +12 -0
  8. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/conversation.py +1 -1
  9. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/logic/best_match.py +11 -2
  10. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/logic/llm_adapters.py +2 -2
  11. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/logic/logic_adapter.py +20 -3
  12. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/logic/mathematical_evaluation.py +15 -2
  13. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/parsing.py +16 -12
  14. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/storage/sql_storage.py +11 -4
  15. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/trainers.py +8 -7
  16. {chatterbot-1.2.16 → chatterbot-1.2.18}/pyproject.toml +6 -6
  17. {chatterbot-1.2.16 → chatterbot-1.2.18}/tests/test_chatbot.py +117 -2
  18. {chatterbot-1.2.16 → chatterbot-1.2.18}/tests/test_conversations.py +35 -0
  19. {chatterbot-1.2.16 → chatterbot-1.2.18}/tests/test_parsing.py +56 -1
  20. chatterbot-1.2.18/tests/test_past_date_quantities.py +44 -0
  21. {chatterbot-1.2.16 → chatterbot-1.2.18}/ChatterBot.egg-info/dependency_links.txt +0 -0
  22. {chatterbot-1.2.16 → chatterbot-1.2.18}/ChatterBot.egg-info/top_level.txt +0 -0
  23. {chatterbot-1.2.16 → chatterbot-1.2.18}/LICENSE +0 -0
  24. {chatterbot-1.2.16 → chatterbot-1.2.18}/README.md +0 -0
  25. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/__main__.py +0 -0
  26. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/adapters.py +0 -0
  27. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/components.py +0 -0
  28. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/constants.py +0 -0
  29. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/corpus.py +0 -0
  30. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/exceptions.py +0 -0
  31. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/__init__.py +0 -0
  32. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/__init__.py +0 -0
  33. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/abstract_models.py +0 -0
  34. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/admin.py +0 -0
  35. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/apps.py +0 -0
  36. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/migrations/0001_initial.py +0 -0
  37. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/migrations/0002_statement_extra_data.py +0 -0
  38. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/migrations/0003_change_occurrence_default.py +0 -0
  39. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/migrations/0004_rename_in_response_to.py +0 -0
  40. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/migrations/0005_statement_created_at.py +0 -0
  41. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/migrations/0006_create_conversation.py +0 -0
  42. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/migrations/0007_response_created_at.py +0 -0
  43. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/migrations/0008_update_conversations.py +0 -0
  44. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/migrations/0009_tags.py +0 -0
  45. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/migrations/0010_statement_text.py +0 -0
  46. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/migrations/0011_blank_extra_data.py +0 -0
  47. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/migrations/0012_statement_created_at.py +0 -0
  48. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/migrations/0013_change_conversations.py +0 -0
  49. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/migrations/0014_remove_statement_extra_data.py +0 -0
  50. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/migrations/0015_statement_persona.py +0 -0
  51. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/migrations/0016_statement_stemmed_text.py +0 -0
  52. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/migrations/0017_tags_unique.py +0 -0
  53. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/migrations/0018_text_max_length.py +0 -0
  54. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/migrations/0019_alter_statement_id_alter_tag_id_and_more.py +0 -0
  55. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/migrations/0020_alter_statement_conversation_and_more.py +0 -0
  56. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/migrations/0021_increase_text_max_length_to_1100.py +0 -0
  57. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/migrations/__init__.py +0 -0
  58. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/model_admin.py +0 -0
  59. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/models.py +0 -0
  60. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/django_chatterbot/settings.py +0 -0
  61. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/sqlalchemy_app/__init__.py +0 -0
  62. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/ext/sqlalchemy_app/models.py +0 -0
  63. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/filters.py +0 -0
  64. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/languages.py +0 -0
  65. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/logic/__init__.py +0 -0
  66. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/logic/mcp_tools.py +0 -0
  67. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/logic/specific_response.py +0 -0
  68. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/logic/time_adapter.py +0 -0
  69. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/logic/unit_conversion.py +0 -0
  70. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/preprocessors.py +0 -0
  71. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/response_selection.py +0 -0
  72. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/search.py +0 -0
  73. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/storage/__init__.py +0 -0
  74. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/storage/django_storage.py +0 -0
  75. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/storage/mongodb.py +0 -0
  76. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/storage/redis.py +0 -0
  77. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/storage/storage_adapter.py +0 -0
  78. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/tagging.py +0 -0
  79. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/utils.py +0 -0
  80. {chatterbot-1.2.16 → chatterbot-1.2.18}/chatterbot/vectorstores.py +0 -0
  81. {chatterbot-1.2.16 → chatterbot-1.2.18}/setup.cfg +0 -0
  82. {chatterbot-1.2.16 → chatterbot-1.2.18}/tests/test_adapter_validation.py +0 -0
  83. {chatterbot-1.2.16 → chatterbot-1.2.18}/tests/test_benchmarks.py +0 -0
  84. {chatterbot-1.2.16 → chatterbot-1.2.18}/tests/test_cli.py +0 -0
  85. {chatterbot-1.2.16 → chatterbot-1.2.18}/tests/test_comparisons.py +0 -0
  86. {chatterbot-1.2.16 → chatterbot-1.2.18}/tests/test_corpus.py +0 -0
  87. {chatterbot-1.2.16 → chatterbot-1.2.18}/tests/test_examples.py +0 -0
  88. {chatterbot-1.2.16 → chatterbot-1.2.18}/tests/test_filters.py +0 -0
  89. {chatterbot-1.2.16 → chatterbot-1.2.18}/tests/test_initialization.py +0 -0
  90. {chatterbot-1.2.16 → chatterbot-1.2.18}/tests/test_languages.py +0 -0
  91. {chatterbot-1.2.16 → chatterbot-1.2.18}/tests/test_preprocessors.py +0 -0
  92. {chatterbot-1.2.16 → chatterbot-1.2.18}/tests/test_response_selection.py +0 -0
  93. {chatterbot-1.2.16 → chatterbot-1.2.18}/tests/test_search.py +0 -0
  94. {chatterbot-1.2.16 → chatterbot-1.2.18}/tests/test_tagging.py +0 -0
  95. {chatterbot-1.2.16 → chatterbot-1.2.18}/tests/test_turing.py +0 -0
  96. {chatterbot-1.2.16 → chatterbot-1.2.18}/tests/test_utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ChatterBot
3
- Version: 1.2.16
3
+ Version: 1.2.18
4
4
  Summary: ChatterBot is a machine learning, conversational dialog engine
5
5
  Author: Gunther Cox
6
6
  License-Expression: BSD-3-Clause
@@ -42,7 +42,7 @@ Requires-Dist: coverage; extra == "test"
42
42
  Requires-Dist: sphinx<9.2,>=5.3; extra == "test"
43
43
  Requires-Dist: sphinx-sitemap>=2.6.0; extra == "test"
44
44
  Requires-Dist: huggingface_hub; extra == "test"
45
- Requires-Dist: django<6.0,>=5.2.15; extra == "test"
45
+ Requires-Dist: django<6.0,>=5.2.16; extra == "test"
46
46
  Provides-Extra: dev
47
47
  Requires-Dist: pint>=0.8.1; extra == "dev"
48
48
  Requires-Dist: pyyaml<7.0,>=6.0; extra == "dev"
@@ -50,13 +50,13 @@ Requires-Dist: chatterbot-corpus<1.3.0,>=1.2.2; extra == "dev"
50
50
  Requires-Dist: ollama<1.0,>=0.6.0; extra == "dev"
51
51
  Requires-Dist: openai; extra == "dev"
52
52
  Provides-Extra: redis
53
- Requires-Dist: redis[hiredis]<7.3,>=7.0; extra == "redis"
54
- Requires-Dist: langchain-redis<0.3.0; extra == "redis"
53
+ Requires-Dist: redis[hiredis]<8.2,>=7.0; extra == "redis"
54
+ Requires-Dist: langchain-redis<=0.3.1; extra == "redis"
55
55
  Requires-Dist: langchain-huggingface<1.3.0,>=0.1.2; extra == "redis"
56
- Requires-Dist: accelerate<1.14,>=1.6.0; extra == "redis"
57
- Requires-Dist: sentence-transformers<5.3.0,>=4.0.2; extra == "redis"
56
+ Requires-Dist: accelerate<1.17,>=1.6.0; extra == "redis"
57
+ Requires-Dist: sentence-transformers<6.4.0,>=4.0.2; extra == "redis"
58
58
  Provides-Extra: mongodb
59
- Requires-Dist: pymongo<4.17,>=4.11; extra == "mongodb"
59
+ Requires-Dist: pymongo<4.21,>=4.11; extra == "mongodb"
60
60
  Dynamic: license-file
61
61
 
62
62
  ![ChatterBot: Machine learning in Python](https://i.imgur.com/b3SCmGT.png)
@@ -86,6 +86,7 @@ tests/test_filters.py
86
86
  tests/test_initialization.py
87
87
  tests/test_languages.py
88
88
  tests/test_parsing.py
89
+ tests/test_past_date_quantities.py
89
90
  tests/test_preprocessors.py
90
91
  tests/test_response_selection.py
91
92
  tests/test_search.py
@@ -12,14 +12,14 @@ ollama<1.0,>=0.6.0
12
12
  openai
13
13
 
14
14
  [mongodb]
15
- pymongo<4.17,>=4.11
15
+ pymongo<4.21,>=4.11
16
16
 
17
17
  [redis]
18
- redis[hiredis]<7.3,>=7.0
19
- langchain-redis<0.3.0
18
+ redis[hiredis]<8.2,>=7.0
19
+ langchain-redis<=0.3.1
20
20
  langchain-huggingface<1.3.0,>=0.1.2
21
- accelerate<1.14,>=1.6.0
22
- sentence-transformers<5.3.0,>=4.0.2
21
+ accelerate<1.17,>=1.6.0
22
+ sentence-transformers<6.4.0,>=4.0.2
23
23
 
24
24
  [test]
25
25
  flake8
@@ -27,4 +27,4 @@ coverage
27
27
  sphinx<9.2,>=5.3
28
28
  sphinx-sitemap>=2.6.0
29
29
  huggingface_hub
30
- django<6.0,>=5.2.15
30
+ django<6.0,>=5.2.16
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ChatterBot
3
- Version: 1.2.16
3
+ Version: 1.2.18
4
4
  Summary: ChatterBot is a machine learning, conversational dialog engine
5
5
  Author: Gunther Cox
6
6
  License-Expression: BSD-3-Clause
@@ -42,7 +42,7 @@ Requires-Dist: coverage; extra == "test"
42
42
  Requires-Dist: sphinx<9.2,>=5.3; extra == "test"
43
43
  Requires-Dist: sphinx-sitemap>=2.6.0; extra == "test"
44
44
  Requires-Dist: huggingface_hub; extra == "test"
45
- Requires-Dist: django<6.0,>=5.2.15; extra == "test"
45
+ Requires-Dist: django<6.0,>=5.2.16; extra == "test"
46
46
  Provides-Extra: dev
47
47
  Requires-Dist: pint>=0.8.1; extra == "dev"
48
48
  Requires-Dist: pyyaml<7.0,>=6.0; extra == "dev"
@@ -50,13 +50,13 @@ Requires-Dist: chatterbot-corpus<1.3.0,>=1.2.2; extra == "dev"
50
50
  Requires-Dist: ollama<1.0,>=0.6.0; extra == "dev"
51
51
  Requires-Dist: openai; extra == "dev"
52
52
  Provides-Extra: redis
53
- Requires-Dist: redis[hiredis]<7.3,>=7.0; extra == "redis"
54
- Requires-Dist: langchain-redis<0.3.0; extra == "redis"
53
+ Requires-Dist: redis[hiredis]<8.2,>=7.0; extra == "redis"
54
+ Requires-Dist: langchain-redis<=0.3.1; extra == "redis"
55
55
  Requires-Dist: langchain-huggingface<1.3.0,>=0.1.2; extra == "redis"
56
- Requires-Dist: accelerate<1.14,>=1.6.0; extra == "redis"
57
- Requires-Dist: sentence-transformers<5.3.0,>=4.0.2; extra == "redis"
56
+ Requires-Dist: accelerate<1.17,>=1.6.0; extra == "redis"
57
+ Requires-Dist: sentence-transformers<6.4.0,>=4.0.2; extra == "redis"
58
58
  Provides-Extra: mongodb
59
- Requires-Dist: pymongo<4.17,>=4.11; extra == "mongodb"
59
+ Requires-Dist: pymongo<4.21,>=4.11; extra == "mongodb"
60
60
  Dynamic: license-file
61
61
 
62
62
  ![ChatterBot: Machine learning in Python](https://i.imgur.com/b3SCmGT.png)
@@ -4,7 +4,7 @@ ChatterBot is a machine learning, conversational dialog engine.
4
4
  from .chatterbot import ChatBot
5
5
 
6
6
 
7
- __version__ = '1.2.16'
7
+ __version__ = '1.2.18'
8
8
 
9
9
  __all__ = (
10
10
  'ChatBot',
@@ -31,9 +31,13 @@ class ChatBot(object):
31
31
  :type tagger: object
32
32
 
33
33
  :param tagger_language: The language to use for the tagger.
34
- Defaults to :class:`~chatterbot.languages.ENG`.
34
+ Defaults to ``language`` if provided, otherwise
35
+ :class:`~chatterbot.languages.ENG`.
35
36
  :type tagger_language: object
36
37
 
38
+ :param language: The language to use when no ``tagger_language`` is provided.
39
+ :type language: object
40
+
37
41
  :param preprocessors: A list of preprocessor functions to use for the chat bot.
38
42
  :type preprocessors: list
39
43
 
@@ -81,7 +85,10 @@ class ChatBot(object):
81
85
 
82
86
  self.storage = utils.initialize_class(storage_adapter, **kwargs)
83
87
 
84
- tagger_language = kwargs.get('tagger_language', languages.ENG)
88
+ tagger_language = kwargs.get(
89
+ 'tagger_language',
90
+ kwargs.get('language', languages.ENG)
91
+ )
85
92
 
86
93
  # Check if storage adapter has a preferred tagger
87
94
  PreferredTagger = self.storage.get_preferred_tagger()
@@ -137,6 +144,9 @@ class ChatBot(object):
137
144
  self.logger.info(f'Storage adapter prefers search algorithm: {preferred_search_algorithm}')
138
145
  kwargs.setdefault('search_algorithm_name', preferred_search_algorithm)
139
146
 
147
+ # NOTE: 'xx' is the language code for a multi-language model
148
+ self.nlp = spacy.blank(self.tagger.language.ISO_639_1)
149
+
140
150
  for adapter in logic_adapters:
141
151
  utils.validate_adapter_class(adapter, LogicAdapter)
142
152
  logic_adapter = utils.initialize_class(adapter, self, **kwargs)
@@ -153,9 +163,6 @@ class ChatBot(object):
153
163
  for preprocessor in preprocessors:
154
164
  self.preprocessors.append(utils.import_module(preprocessor))
155
165
 
156
- # NOTE: 'xx' is the language code for a multi-language model
157
- self.nlp = spacy.blank(self.tagger.language.ISO_639_1)
158
-
159
166
  # Allow the bot to save input it receives so that it can learn
160
167
  self.read_only = kwargs.get('read_only', False)
161
168
 
@@ -279,6 +286,7 @@ class ChatBot(object):
279
286
  results = []
280
287
  result = None
281
288
  max_confidence = -1
289
+ has_confident_response = False
282
290
 
283
291
  for adapter in self.logic_adapters:
284
292
  if adapter.can_process(input_statement):
@@ -295,6 +303,9 @@ class ChatBot(object):
295
303
  if output.confidence > max_confidence:
296
304
  result = output
297
305
  max_confidence = output.confidence
306
+
307
+ if output.confidence >= adapter.maximum_similarity_threshold:
308
+ has_confident_response = True
298
309
  else:
299
310
  self.logger.info(
300
311
  'Not processing the statement using {}'.format(adapter.class_name)
@@ -337,6 +348,12 @@ class ChatBot(object):
337
348
  f'No logic adapter was able to process the statement "{input_statement.text}".'
338
349
  )
339
350
 
351
+ if not has_confident_response:
352
+ for adapter in self.logic_adapters:
353
+ if adapter.default_responses:
354
+ result = adapter.get_default_response(input_statement)
355
+ break
356
+
340
357
  response = Statement(
341
358
  text=result.text,
342
359
  in_response_to=input_statement.text,
@@ -366,6 +383,8 @@ class ChatBot(object):
366
383
 
367
384
  if not isinstance(previous_statement, (str, type(None), )):
368
385
  statement.in_response_to = previous_statement.text
386
+ if isinstance(previous_statement, Statement):
387
+ statement.search_in_response_to = previous_statement.search_text
369
388
  elif isinstance(previous_statement, str):
370
389
  statement.in_response_to = previous_statement
371
390
 
@@ -12,6 +12,9 @@ class Comparator:
12
12
  Base class establishing the interface that all comparators should implement.
13
13
  """
14
14
 
15
+ # Default maximum_similarity_threshold for search stopping and fallback acceptance.
16
+ default_threshold = 0.95
17
+
15
18
  def __init__(self, language):
16
19
 
17
20
  self.language = language
@@ -44,6 +47,9 @@ class LevenshteinDistance(Comparator):
44
47
  based on the Levenshtein distance algorithm.
45
48
  """
46
49
 
50
+ # Default maximum_similarity_threshold for search stopping and fallback acceptance.
51
+ default_threshold = 0.70
52
+
47
53
  def compare_text(self, text_a: str, text_b: str) -> float:
48
54
  """
49
55
  Compare the two pieces of text.
@@ -97,6 +103,9 @@ class SpacySimilarity(Comparator):
97
103
 
98
104
  """
99
105
 
106
+ # Default maximum_similarity_threshold for search stopping and fallback acceptance.
107
+ default_threshold = 0.70
108
+
100
109
  def __init__(self, language):
101
110
  super().__init__(language)
102
111
 
@@ -148,6 +157,9 @@ class JaccardSimilarity(Comparator):
148
157
  .. _`Jaccard similarity index`: https://en.wikipedia.org/wiki/Jaccard_index
149
158
  """
150
159
 
160
+ # Default maximum_similarity_threshold for search stopping and fallback acceptance.
161
+ default_threshold = 0.50
162
+
151
163
  def __init__(self, language):
152
164
  super().__init__(language)
153
165
 
@@ -89,7 +89,7 @@ class Statement(StatementMixin):
89
89
  self.tags = kwargs.pop('tags', [])
90
90
  self.in_response_to = in_response_to
91
91
  self.search_in_response_to = kwargs.get('search_in_response_to', '')
92
- self.created_at = kwargs.get('created_at', datetime.now())
92
+ self.created_at = kwargs.get('created_at', datetime.now(timezone.utc))
93
93
 
94
94
  if not isinstance(self.created_at, datetime):
95
95
  self.created_at = date_parser.parse(self.created_at)
@@ -105,8 +105,17 @@ class BestMatch(LogicAdapter):
105
105
  additional_response_selection_parameters
106
106
  )
107
107
 
108
- # Get all statements with text similar to the closest match
109
- response_list = list(self.chatbot.storage.filter(**response_selection_parameters))
108
+ exact_response_selection_parameters = dict(response_selection_parameters)
109
+ exact_response_selection_parameters.pop('search_text', None)
110
+ exact_response_selection_parameters['in_response_to'] = (
111
+ closest_match.in_response_to or input_statement.text
112
+ )
113
+
114
+ response_list = list(self.chatbot.storage.filter(**exact_response_selection_parameters))
115
+
116
+ if not response_list:
117
+ # Fall back to indexed text to support normalized variations.
118
+ response_list = list(self.chatbot.storage.filter(**response_selection_parameters))
110
119
 
111
120
  if response_list:
112
121
  response = self.select_response(
@@ -701,7 +701,7 @@ class OpenAILogicAdapter(LLMLogicAdapter):
701
701
  This adapter is experimental.
702
702
 
703
703
  Configuration:
704
- model (str): OpenAI model name (e.g., 'gpt-4', 'gpt-3.5-turbo')
704
+ model (str): OpenAI model name (e.g., 'gpt-5.4-mini')
705
705
  host (str): Optional custom API endpoint
706
706
  logic_adapters_as_tools (list): Logic adapters to expose as tools
707
707
 
@@ -711,7 +711,7 @@ class OpenAILogicAdapter(LLMLogicAdapter):
711
711
  Example:
712
712
  {
713
713
  'import_path': 'chatterbot.logic.OpenAILogicAdapter',
714
- 'model': 'gpt-4o-mini',
714
+ 'model': 'gpt-5.4-mini',
715
715
  'logic_adapters_as_tools': [
716
716
  'chatterbot.logic.MathematicalEvaluation',
717
717
  'chatterbot.logic.TimeLogicAdapter'
@@ -1,3 +1,4 @@
1
+ from copy import copy
1
2
  from random import choice
2
3
 
3
4
  from chatterbot.adapters import Adapter
@@ -20,8 +21,8 @@ class LogicAdapter(Adapter):
20
21
  The maximum amount of similarity between two statement that is required
21
22
  before the search process is halted. The search for a matching statement
22
23
  will continue until a statement with a greater than or equal similarity
23
- is found or the search set is exhausted.
24
- Defaults to 0.95
24
+ is found or the search set is exhausted. Defaults to the selected
25
+ comparison function's ``default_threshold``.
25
26
 
26
27
  :param response_selection_method:
27
28
  The a response selection method.
@@ -47,8 +48,24 @@ class LogicAdapter(Adapter):
47
48
  self.search_algorithm_name
48
49
  ]
49
50
 
51
+ statement_comparison_function = kwargs.get('statement_comparison_function')
52
+
53
+ if statement_comparison_function is not None and hasattr(self.search_algorithm, 'compare_statements'):
54
+ if isinstance(statement_comparison_function, str):
55
+ statement_comparison_function = utils.import_module(
56
+ statement_comparison_function
57
+ )
58
+
59
+ self.search_algorithm = copy(self.search_algorithm)
60
+ self.search_algorithm.compare_statements = statement_comparison_function(
61
+ language=self.chatbot.tagger.language
62
+ )
63
+
64
+ comparison_function = getattr(self.search_algorithm, 'compare_statements', None)
65
+ default_threshold = getattr(comparison_function, 'default_threshold', 0.95)
66
+
50
67
  self.maximum_similarity_threshold = kwargs.get(
51
- 'maximum_similarity_threshold', 0.95
68
+ 'maximum_similarity_threshold', default_threshold
52
69
  )
53
70
 
54
71
  if response_selection_method := kwargs.get('response_selection_method'):
@@ -21,11 +21,16 @@ class MathematicalEvaluation(LogicAdapter, MCPToolAdapter):
21
21
  """
22
22
 
23
23
  def __init__(self, chatbot, **kwargs):
24
+ from mathparse import mathwords
25
+
24
26
  super().__init__(chatbot, **kwargs)
25
27
 
26
28
  self.language = kwargs.get('language', languages.ENG)
27
29
  self.cache = {}
28
30
 
31
+ math_words = mathwords.MATH_WORDS.get(self.language.ISO_639.upper(), {})
32
+ self.stop_words: set = chatbot.nlp.Defaults.stop_words - set(math_words.get('scales', {}))
33
+
29
34
  def can_process(self, statement) -> bool:
30
35
  """
31
36
  Determines whether it is appropriate for this
@@ -58,7 +63,11 @@ class MathematicalEvaluation(LogicAdapter, MCPToolAdapter):
58
63
  try:
59
64
  response.text = '{} = {}'.format(
60
65
  response.text,
61
- mathparse.parse(expression, language=self.language.ISO_639.upper())
66
+ mathparse.parse(
67
+ expression,
68
+ language=self.language.ISO_639.upper(),
69
+ stopwords=self.stop_words
70
+ )
62
71
  )
63
72
 
64
73
  # The confidence is 1 if the expression could be evaluated
@@ -109,7 +118,11 @@ class MathematicalEvaluation(LogicAdapter, MCPToolAdapter):
109
118
  extracted = mathparse.extract_expression(expression, language=self.language.ISO_639.upper())
110
119
 
111
120
  # Evaluate the expression
112
- result = mathparse.parse(extracted, language=self.language.ISO_639.upper())
121
+ result = mathparse.parse(
122
+ extracted,
123
+ language=self.language.ISO_639.upper(),
124
+ stopwords=self.stop_words
125
+ )
113
126
 
114
127
  return f"{extracted} = {result}"
115
128
 
@@ -548,13 +548,12 @@ def date_from_quarter(base_date: datetime, ordinal: int, year: int) -> list[date
548
548
  """
549
549
  Extract date from quarter of a year
550
550
  """
551
+ # The "last" ordinal refers to the fourth quarter.
552
+ if ordinal < 1:
553
+ ordinal = 4
551
554
  interval = 3
552
- month_start = interval * (ordinal - 1)
553
- if month_start < 0:
554
- month_start = 9
555
- month_end = month_start + interval
556
- if month_start == 0:
557
- month_start = 1
555
+ month_start = interval * (ordinal - 1) + 1
556
+ month_end = month_start + interval - 1
558
557
  return [
559
558
  datetime(year, month_start, 1),
560
559
  datetime(year, month_end, calendar.monthrange(year, month_end)[1])
@@ -597,7 +596,7 @@ def date_from_relative_week_year(base_date: datetime, time: str, dow: str, ordin
597
596
  if time == 'this' or time == 'coming':
598
597
  return datetime(relative_date.year, 1, 1)
599
598
  elif time == 'last' or time == 'previous':
600
- return datetime(relative_date.year - 1, relative_date.month, 1)
599
+ return datetime(relative_date.year - ord, relative_date.month, 1)
601
600
  elif time == 'next' or time == 'following':
602
601
  return relative_date + timedelta(ord * 365)
603
602
  elif time == 'end of the':
@@ -606,7 +605,13 @@ def date_from_relative_week_year(base_date: datetime, time: str, dow: str, ordin
606
605
  if time == 'this':
607
606
  return datetime(relative_date.year, relative_date.month, relative_date.day)
608
607
  elif time == 'last' or time == 'previous':
609
- return datetime(relative_date.year, relative_date.month - 1, relative_date.day)
608
+ # Move across year boundaries and keep the day within the
609
+ # valid range of the target month
610
+ month_index = relative_date.month - 1 - ord
611
+ year = relative_date.year + month_index // 12
612
+ month = month_index % 12 + 1
613
+ day = min(relative_date.day, calendar.monthrange(year, month)[1])
614
+ return datetime(year, month, day)
610
615
  elif time == 'next' or time == 'following':
611
616
  if relative_date.month + ord >= 12:
612
617
  month = relative_date.month - 1 + ord
@@ -629,17 +634,16 @@ def date_from_relative_week_year(base_date: datetime, time: str, dow: str, ordin
629
634
  if time == 'this':
630
635
  return relative_date - timedelta(days=relative_date.weekday())
631
636
  elif time == 'last' or time == 'previous':
632
- return relative_date - timedelta(weeks=1)
637
+ return relative_date - timedelta(weeks=ord)
633
638
  elif time == 'next' or time == 'following':
634
639
  return relative_date + timedelta(weeks=ord)
635
640
  elif time == 'end of the':
636
- day_of_week = base_date.weekday()
637
- return day_of_week + timedelta(days=6 - relative_date.weekday())
641
+ return relative_date + timedelta(days=6 - relative_date.weekday())
638
642
  elif dow in day_variations:
639
643
  if time == 'this':
640
644
  return relative_date
641
645
  elif time == 'last' or time == 'previous':
642
- return relative_date - timedelta(days=1)
646
+ return relative_date - timedelta(days=ord)
643
647
  elif time == 'next' or time == 'following':
644
648
  return relative_date + timedelta(days=ord)
645
649
  elif time == 'end of the':
@@ -23,6 +23,7 @@ class SQLStorageAdapter(StorageAdapter):
23
23
  from sqlalchemy import create_engine, inspect, event
24
24
  from sqlalchemy import Index
25
25
  from sqlalchemy.engine import Engine
26
+ from sqlalchemy.engine.url import make_url
26
27
  from sqlalchemy.orm import sessionmaker, scoped_session
27
28
 
28
29
  self.database_uri = kwargs.get('database_uri', False)
@@ -40,7 +41,7 @@ class SQLStorageAdapter(StorageAdapter):
40
41
  # PostgreSQL, MySQL, etc. use QueuePool which does support them
41
42
  pool_config = {}
42
43
 
43
- if self.database_uri.startswith('sqlite://'):
44
+ if make_url(self.database_uri).get_backend_name() == 'sqlite':
44
45
 
45
46
  @event.listens_for(Engine, 'connect')
46
47
  def set_sqlite_pragma(dbapi_connection, connection_record):
@@ -154,13 +155,19 @@ class SQLStorageAdapter(StorageAdapter):
154
155
  Removes any responses from statements where the response text matches
155
156
  the input text.
156
157
  """
158
+ from chatterbot.ext.sqlalchemy_app.models import tag_association_table
159
+
157
160
  Statement = self.get_model('statement')
158
161
  session = self.Session()
159
162
  try:
160
163
  query = session.query(Statement).filter_by(text=statement_text)
161
- record = query.first()
162
-
163
- session.delete(record)
164
+ matching_ids = query.with_entities(Statement.id)
165
+ session.execute(
166
+ tag_association_table.delete().where(
167
+ tag_association_table.c.statement_id.in_(matching_ids)
168
+ )
169
+ )
170
+ query.delete(synchronize_session=False)
164
171
  session.commit()
165
172
  finally:
166
173
  session.close()
@@ -368,7 +368,7 @@ class GenericFileTrainer(Trainer):
368
368
  context = {
369
369
  key: row[value]
370
370
  for key, value in self.field_map.items()
371
- if key != text_row
371
+ if key != 'text'
372
372
  }
373
373
  contexts.append(context)
374
374
 
@@ -424,14 +424,15 @@ class GenericFileTrainer(Trainer):
424
424
  n_process=1
425
425
  )
426
426
 
427
- for document in response_documents:
427
+ # Use the original response text as the metadata lookup key.
428
+ for response_text, document in zip(response_texts, response_documents):
428
429
  # Handle both spaCy Doc objects and plain strings from NoOpTagger
429
430
  if isinstance(document, str):
430
431
  # NoOpTagger returns plain strings
431
- response_to_search_index_mapping[document] = self.chatbot.tagger.get_text_index_string(document)
432
+ response_to_search_index_mapping[response_text] = self.chatbot.tagger.get_text_index_string(document)
432
433
  else:
433
434
  # Regular taggers return spaCy Doc objects
434
- response_to_search_index_mapping[document.text] = document._.search_index
435
+ response_to_search_index_mapping[response_text] = document._.search_index
435
436
 
436
437
  # Create statements from processed documents
437
438
  for document, context in tqdm(documents_list, desc='Creating statements', disable=self.disable_progress, leave=False):
@@ -444,7 +445,7 @@ class GenericFileTrainer(Trainer):
444
445
  # Regular taggers return spaCy Doc objects
445
446
  statement_text = document.text
446
447
  statement_search_text = document._.search_index
447
-
448
+
448
449
  statement = Statement(
449
450
  text=statement_text,
450
451
  conversation=context.get('conversation', 'training'),
@@ -460,9 +461,9 @@ class GenericFileTrainer(Trainer):
460
461
  # Use the in_response_to attribute for the previous statement if
461
462
  # one is defined, otherwise use the last statement which was created
462
463
  if 'in_response_to' in self.field_map.keys():
463
- statement.in_response_to = context.get(self.field_map['in_response_to'], None)
464
+ statement.in_response_to = context.get('in_response_to')
464
465
  statement.search_in_response_to = response_to_search_index_mapping.get(
465
- context.get(self.field_map['in_response_to'], None), ''
466
+ statement.in_response_to, ''
466
467
  )
467
468
  else:
468
469
  # List-type data such as CSVs with no response specified can use
@@ -74,7 +74,7 @@ test = [
74
74
  "sphinx>=5.3,<9.2",
75
75
  "sphinx-sitemap>=2.6.0",
76
76
  "huggingface_hub",
77
- "django>=5.2.15,<6.0"
77
+ "django>=5.2.16,<6.0"
78
78
  ]
79
79
  dev = [
80
80
  "pint>=0.8.1",
@@ -84,12 +84,12 @@ dev = [
84
84
  "openai"
85
85
  ]
86
86
  redis = [
87
- "redis[hiredis]>=7.0,<7.3",
88
- "langchain-redis<0.3.0",
87
+ "redis[hiredis]>=7.0,<8.2",
88
+ "langchain-redis<=0.3.1",
89
89
  "langchain-huggingface>=0.1.2,<1.3.0",
90
- "accelerate>=1.6.0,<1.14",
91
- "sentence-transformers>=4.0.2,<5.3.0",
90
+ "accelerate>=1.6.0,<1.17",
91
+ "sentence-transformers>=4.0.2,<6.4.0",
92
92
  ]
93
93
  mongodb = [
94
- "pymongo>=4.11,<4.17",
94
+ "pymongo>=4.11,<4.21",
95
95
  ]
@@ -1,8 +1,10 @@
1
1
  from tests.base_case import ChatBotTestCase
2
2
  from chatterbot import ChatBot
3
- from chatterbot.logic import LogicAdapter, MathematicalEvaluation
3
+ from chatterbot import comparisons, utils
4
+ from chatterbot.logic import BestMatch, LogicAdapter, MathematicalEvaluation
4
5
  from chatterbot.conversation import Statement
5
6
  from chatterbot import languages
7
+ from chatterbot.tagging import NoOpTagger
6
8
 
7
9
 
8
10
  class ChatBotInitializationTestCase(ChatBotTestCase):
@@ -45,6 +47,29 @@ class ChatBotInitializationTestCase(ChatBotTestCase):
45
47
  str(exc.exception),
46
48
  )
47
49
 
50
+ def test_language_is_used_as_tagger_language_default(self):
51
+ chatbot = ChatBot(
52
+ 'Test Bot',
53
+ language=languages.GER,
54
+ tagger=NoOpTagger,
55
+ database_uri=None
56
+ )
57
+ self.addCleanup(chatbot.storage.close)
58
+
59
+ self.assertIs(chatbot.tagger.language, languages.GER)
60
+
61
+ def test_tagger_language_overrides_language(self):
62
+ chatbot = ChatBot(
63
+ 'Test Bot',
64
+ language=languages.GER,
65
+ tagger_language=languages.ENG,
66
+ tagger=NoOpTagger,
67
+ database_uri=None
68
+ )
69
+ self.addCleanup(chatbot.storage.close)
70
+
71
+ self.assertIs(chatbot.tagger.language, languages.ENG)
72
+
48
73
 
49
74
  class ChatterBotResponseTestCase(ChatBotTestCase):
50
75
 
@@ -304,12 +329,17 @@ class ChatterBotResponseTestCase(ChatBotTestCase):
304
329
  self.assertEqual(response.confidence, 0)
305
330
 
306
331
  def test_learn_response(self):
307
- previous_response = Statement(text='Define Hemoglobin.')
332
+ previous_response = Statement(
333
+ text='Define Hemoglobin.',
334
+ search_text='PRECOMPUTED_INDEX'
335
+ )
308
336
  statement = Statement(text='Hemoglobin is an oxygen-transport metalloprotein.')
309
337
  self.chatbot.learn_response(statement, previous_response)
310
338
  results = list(self.chatbot.storage.filter(text=statement.text))
311
339
 
312
340
  self.assertIsLength(results, 1)
341
+ self.assertEqual(results[0].in_response_to, previous_response.text)
342
+ self.assertEqual(results[0].search_in_response_to, previous_response.search_text)
313
343
 
314
344
  def test_get_response_does_not_add_new_statement(self):
315
345
  """
@@ -401,6 +431,77 @@ class TestAdapterC(LogicAdapter):
401
431
 
402
432
  class ChatBotLogicAdapterTestCase(ChatBotTestCase):
403
433
 
434
+ def test_adapter_comparison_functions_are_isolated(self):
435
+ self.chatbot.logic_adapters = [
436
+ utils.initialize_class(
437
+ {
438
+ 'import_path': 'chatterbot.logic.BestMatch',
439
+ 'statement_comparison_function': 'chatterbot.comparisons.JaccardSimilarity'
440
+ },
441
+ self.chatbot
442
+ ),
443
+ BestMatch(
444
+ self.chatbot,
445
+ statement_comparison_function=comparisons.LevenshteinDistance
446
+ )
447
+ ]
448
+
449
+ self.assertIsInstance(
450
+ self.chatbot.logic_adapters[0].search_algorithm.compare_statements,
451
+ comparisons.JaccardSimilarity
452
+ )
453
+ self.assertIsInstance(
454
+ self.chatbot.logic_adapters[1].search_algorithm.compare_statements,
455
+ comparisons.LevenshteinDistance
456
+ )
457
+ self.assertIsNot(
458
+ self.chatbot.logic_adapters[0].search_algorithm,
459
+ self.chatbot.logic_adapters[1].search_algorithm
460
+ )
461
+ self.assertIsInstance(
462
+ self.chatbot.search_algorithms['indexed_text_search'].compare_statements,
463
+ comparisons.LevenshteinDistance
464
+ )
465
+ self.assertEqual(self.chatbot.logic_adapters[0].maximum_similarity_threshold, 0.5)
466
+ self.assertEqual(self.chatbot.logic_adapters[1].maximum_similarity_threshold, 0.7)
467
+
468
+ spacy_adapter = BestMatch(
469
+ self.chatbot,
470
+ statement_comparison_function=comparisons.SpacySimilarity
471
+ )
472
+ self.assertEqual(spacy_adapter.maximum_similarity_threshold, 0.7)
473
+
474
+ overridden_adapter = BestMatch(
475
+ self.chatbot,
476
+ statement_comparison_function=comparisons.LevenshteinDistance,
477
+ maximum_similarity_threshold=0.6
478
+ )
479
+ self.assertEqual(overridden_adapter.maximum_similarity_threshold, 0.6)
480
+
481
+ def test_single_word_query_uses_comparer_default_confidence(self):
482
+ question = 'What is a microprocessor?'
483
+ answer = 'An integrated circuit that implements the functions of a central processing unit of a computer.'
484
+ self._create_with_search_text(text=question)
485
+ self._create_with_search_text(text=answer, in_response_to=question)
486
+
487
+ for comparison_function in (
488
+ comparisons.JaccardSimilarity,
489
+ comparisons.LevenshteinDistance
490
+ ):
491
+ self.chatbot.logic_adapters = [
492
+ BestMatch(
493
+ self.chatbot,
494
+ statement_comparison_function=comparison_function,
495
+ default_response='I do not understand.'
496
+ )
497
+ ]
498
+
499
+ response = self.chatbot.generate_response(
500
+ self._add_search_text(text='microprocessor')
501
+ )
502
+
503
+ self.assertEqual(response.text, answer)
504
+
404
505
  def test_sub_adapter_agreement(self):
405
506
  """
406
507
  In the case that multiple adapters agree on a given
@@ -418,6 +519,20 @@ class ChatBotLogicAdapterTestCase(ChatBotTestCase):
418
519
  self.assertEqual(statement.confidence, 0.5)
419
520
  self.assertEqual(statement.text, 'Good morning.')
420
521
 
522
+ def test_default_response_when_no_adapter_meets_similarity_threshold(self):
523
+ self.chatbot.logic_adapters = [
524
+ TestAdapterA(
525
+ self.chatbot,
526
+ default_response='I do not understand.',
527
+ maximum_similarity_threshold=0.65
528
+ )
529
+ ]
530
+
531
+ response = self.chatbot.generate_response(Statement(text='Something unexpected'))
532
+
533
+ self.assertEqual(response.text, 'I do not understand.')
534
+ self.assertEqual(response.confidence, 0)
535
+
421
536
  def test_no_adapter_can_process_statement(self):
422
537
  """
423
538
  If no logic adapter can process the statement,
@@ -1,4 +1,6 @@
1
+ from datetime import datetime, timedelta, timezone
1
2
  from unittest import TestCase
3
+ from unittest.mock import patch
2
4
  from tests.base_case import ChatBotTestCase
3
5
  from chatterbot import ChatBot
4
6
  from chatterbot.conversation import Statement
@@ -13,6 +15,39 @@ class StatementTests(TestCase):
13
15
  data = self.statement.serialize()
14
16
  self.assertEqual(self.statement.text, data['text'])
15
17
 
18
+ def test_default_created_at_uses_the_current_utc_instant(self):
19
+ expected = datetime(2026, 1, 2, 3, 4, 5, tzinfo=timezone.utc)
20
+
21
+ for offset in (8, -5):
22
+ local_timezone = timezone(timedelta(hours=offset))
23
+
24
+ class LocalDatetime(datetime):
25
+ @classmethod
26
+ def now(cls, tz=None):
27
+ instant = cls(2026, 1, 2, 3, 4, 5, tzinfo=timezone.utc)
28
+ if tz is None:
29
+ return instant.astimezone(local_timezone).replace(tzinfo=None)
30
+ return instant.astimezone(tz)
31
+
32
+ with self.subTest(utc_offset=offset):
33
+ with patch('chatterbot.conversation.datetime', LocalDatetime):
34
+ statement = Statement(text='A timestamped statement.')
35
+
36
+ self.assertEqual(statement.created_at, expected)
37
+ self.assertEqual(statement.created_at.tzinfo, timezone.utc)
38
+
39
+ def test_explicit_aware_created_at_is_preserved(self):
40
+ timestamp = datetime(2026, 1, 2, 3, 4, 5, tzinfo=timezone(timedelta(hours=8)))
41
+ statement = Statement(text='A timestamped statement.', created_at=timestamp)
42
+
43
+ self.assertIs(statement.created_at, timestamp)
44
+
45
+ def test_explicit_naive_created_at_is_assumed_to_be_utc(self):
46
+ timestamp = datetime(2026, 1, 2, 3, 4, 5)
47
+ statement = Statement(text='A timestamped statement.', created_at=timestamp)
48
+
49
+ self.assertEqual(statement.created_at, timestamp.replace(tzinfo=timezone.utc))
50
+
16
51
 
17
52
  class DefaultConversationTestCase(ChatBotTestCase):
18
53
  """
@@ -174,10 +174,27 @@ class DateTimeParsingFunctionIntegrationTestCases(TestCase):
174
174
  input_text = 'Last quarter of 2015'
175
175
  parser = parsing.datetime_parsing(input_text)
176
176
  self.assertIn(input_text, parser[0])
177
- self.assertEqual(parser[0][1][0].strftime('%d-%m-%Y'), '01-09-2015')
177
+ self.assertEqual(parser[0][1][0].strftime('%d-%m-%Y'), '01-10-2015')
178
178
  self.assertEqual(parser[0][1][1].strftime('%d-%m-%Y'), '31-12-2015')
179
179
  self.assertEqual(len(parser), 1)
180
180
 
181
+ def test_calendar_quarter_boundaries(self):
182
+ quarters = [
183
+ ('First', datetime(2016, 1, 1), datetime(2016, 3, 31)),
184
+ ('Second', datetime(2016, 4, 1), datetime(2016, 6, 30)),
185
+ ('Third', datetime(2016, 7, 1), datetime(2016, 9, 30)),
186
+ ('Fourth', datetime(2016, 10, 1), datetime(2016, 12, 31)),
187
+ ('Last', datetime(2016, 10, 1), datetime(2016, 12, 31)),
188
+ ]
189
+ for ordinal, start, end in quarters:
190
+ with self.subTest(quarter=ordinal):
191
+ input_text = f'{ordinal} quarter of 2016'
192
+ result = parsing.datetime_parsing(input_text, self.base_date)
193
+
194
+ self.assertEqual(len(result), 1)
195
+ self.assertEqual(result[0][0], input_text)
196
+ self.assertEqual(result[0][1], [start, end])
197
+
181
198
  def test_captured_pattern_is_next_three_weeks(self):
182
199
  input_text = 'Next 3 weeks'
183
200
  parser = parsing.datetime_parsing(input_text)
@@ -462,6 +479,44 @@ class DateTimeParsingTestCases(TestCase):
462
479
  self.assertEqual(parser[0][1].month, 6)
463
480
  self.assertEqual(parser[0][1].day, 30)
464
481
 
482
+ def test_last_month_from_january(self):
483
+ """
484
+ Test 'last month' from January rolls back to December of the previous year
485
+ """
486
+ base_date = datetime(2025, 1, 15, 12, 0, 0)
487
+ input_text = 'last month'
488
+ parser = parsing.datetime_parsing(input_text, base_date)
489
+
490
+ self.assertEqual(len(parser), 1)
491
+ self.assertEqual(parser[0][1].year, 2024)
492
+ self.assertEqual(parser[0][1].month, 12)
493
+ self.assertEqual(parser[0][1].day, 15)
494
+
495
+ def test_last_month_from_march_31st(self):
496
+ """
497
+ Test 'last month' from March 31 handles February correctly
498
+ """
499
+ base_date = datetime(2025, 3, 31, 12, 0, 0)
500
+ input_text = 'last month'
501
+ parser = parsing.datetime_parsing(input_text, base_date)
502
+
503
+ self.assertEqual(len(parser), 1)
504
+ # February only has 28 days in 2025, should clamp to last valid day
505
+ self.assertEqual(parser[0][1].year, 2025)
506
+ self.assertEqual(parser[0][1].month, 2)
507
+ self.assertEqual(parser[0][1].day, 28)
508
+
509
+ def test_end_of_the_week(self):
510
+ """
511
+ Test 'end of the week' returns the Sunday of the current week
512
+ """
513
+ base_date = datetime(2025, 6, 11, 12, 0, 0) # Wednesday
514
+ input_text = 'end of the week'
515
+ parser = parsing.datetime_parsing(input_text, base_date)
516
+
517
+ self.assertEqual(len(parser), 1)
518
+ self.assertEqual(parser[0][1], datetime(2025, 6, 15))
519
+
465
520
  def test_multiple_datetime_expressions(self):
466
521
  """
467
522
  Test parsing text with multiple date/time references
@@ -0,0 +1,44 @@
1
+ from datetime import datetime
2
+ from unittest import TestCase
3
+
4
+ from chatterbot import parsing
5
+
6
+
7
+ class PastDateQuantityTests(TestCase):
8
+
9
+ def test_past_offsets_use_numeric_and_word_quantities(self):
10
+ base_date = datetime(2026, 1, 31, 15, 30)
11
+ cases = [
12
+ ('last 3 weeks', datetime(2026, 1, 10)),
13
+ ('previous two weeks', datetime(2026, 1, 17)),
14
+ ('previous 2 days', datetime(2026, 1, 29)),
15
+ ('last two days', datetime(2026, 1, 29)),
16
+ ('last 2 months', datetime(2025, 11, 30)),
17
+ ('previous 14 months', datetime(2024, 11, 30)),
18
+ ('last two years', datetime(2024, 1, 1)),
19
+ ]
20
+ for text, expected in cases:
21
+ with self.subTest(text=text):
22
+ result = parsing.datetime_parsing(text, base_date)
23
+
24
+ self.assertEqual(len(result), 1)
25
+ self.assertEqual(result[0][1], expected)
26
+
27
+ def test_past_months_clamp_to_the_target_leap_month(self):
28
+ result = parsing.datetime_parsing('last 13 months', datetime(2025, 3, 31))
29
+
30
+ self.assertEqual(result[0][1], datetime(2024, 2, 29))
31
+
32
+ def test_past_offsets_default_to_one_unit(self):
33
+ base_date = datetime(2026, 1, 31, 15, 30)
34
+ cases = [
35
+ ('last day', datetime(2026, 1, 30)),
36
+ ('previous week', datetime(2026, 1, 24)),
37
+ ('last month', datetime(2025, 12, 31)),
38
+ ('previous year', datetime(2025, 1, 1)),
39
+ ]
40
+ for text, expected in cases:
41
+ with self.subTest(text=text):
42
+ result = parsing.datetime_parsing(text, base_date)
43
+
44
+ self.assertEqual(result[0][1], expected)
File without changes
File without changes
File without changes