ChatterBot 1.2.15__tar.gz → 1.2.17__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 (95) hide show
  1. {chatterbot-1.2.15 → chatterbot-1.2.17}/ChatterBot.egg-info/PKG-INFO +2 -2
  2. {chatterbot-1.2.15 → chatterbot-1.2.17}/ChatterBot.egg-info/requires.txt +1 -1
  3. {chatterbot-1.2.15 → chatterbot-1.2.17}/PKG-INFO +2 -2
  4. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/__init__.py +1 -1
  5. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/chatterbot.py +27 -5
  6. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/comparisons.py +12 -0
  7. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/logic/best_match.py +11 -2
  8. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/logic/logic_adapter.py +20 -3
  9. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/logic/mathematical_evaluation.py +15 -2
  10. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/logic/unit_conversion.py +4 -2
  11. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/trainers.py +77 -18
  12. {chatterbot-1.2.15 → chatterbot-1.2.17}/pyproject.toml +1 -1
  13. {chatterbot-1.2.15 → chatterbot-1.2.17}/tests/test_chatbot.py +123 -1
  14. {chatterbot-1.2.15 → chatterbot-1.2.17}/ChatterBot.egg-info/SOURCES.txt +0 -0
  15. {chatterbot-1.2.15 → chatterbot-1.2.17}/ChatterBot.egg-info/dependency_links.txt +0 -0
  16. {chatterbot-1.2.15 → chatterbot-1.2.17}/ChatterBot.egg-info/top_level.txt +0 -0
  17. {chatterbot-1.2.15 → chatterbot-1.2.17}/LICENSE +0 -0
  18. {chatterbot-1.2.15 → chatterbot-1.2.17}/README.md +0 -0
  19. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/__main__.py +0 -0
  20. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/adapters.py +0 -0
  21. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/components.py +0 -0
  22. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/constants.py +0 -0
  23. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/conversation.py +0 -0
  24. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/corpus.py +0 -0
  25. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/exceptions.py +0 -0
  26. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/__init__.py +0 -0
  27. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/__init__.py +0 -0
  28. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/abstract_models.py +0 -0
  29. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/admin.py +0 -0
  30. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/apps.py +0 -0
  31. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/migrations/0001_initial.py +0 -0
  32. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/migrations/0002_statement_extra_data.py +0 -0
  33. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/migrations/0003_change_occurrence_default.py +0 -0
  34. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/migrations/0004_rename_in_response_to.py +0 -0
  35. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/migrations/0005_statement_created_at.py +0 -0
  36. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/migrations/0006_create_conversation.py +0 -0
  37. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/migrations/0007_response_created_at.py +0 -0
  38. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/migrations/0008_update_conversations.py +0 -0
  39. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/migrations/0009_tags.py +0 -0
  40. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/migrations/0010_statement_text.py +0 -0
  41. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/migrations/0011_blank_extra_data.py +0 -0
  42. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/migrations/0012_statement_created_at.py +0 -0
  43. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/migrations/0013_change_conversations.py +0 -0
  44. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/migrations/0014_remove_statement_extra_data.py +0 -0
  45. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/migrations/0015_statement_persona.py +0 -0
  46. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/migrations/0016_statement_stemmed_text.py +0 -0
  47. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/migrations/0017_tags_unique.py +0 -0
  48. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/migrations/0018_text_max_length.py +0 -0
  49. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/migrations/0019_alter_statement_id_alter_tag_id_and_more.py +0 -0
  50. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/migrations/0020_alter_statement_conversation_and_more.py +0 -0
  51. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/migrations/0021_increase_text_max_length_to_1100.py +0 -0
  52. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/migrations/__init__.py +0 -0
  53. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/model_admin.py +0 -0
  54. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/models.py +0 -0
  55. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/django_chatterbot/settings.py +0 -0
  56. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/sqlalchemy_app/__init__.py +0 -0
  57. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/ext/sqlalchemy_app/models.py +0 -0
  58. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/filters.py +0 -0
  59. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/languages.py +0 -0
  60. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/logic/__init__.py +0 -0
  61. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/logic/llm_adapters.py +0 -0
  62. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/logic/mcp_tools.py +0 -0
  63. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/logic/specific_response.py +0 -0
  64. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/logic/time_adapter.py +0 -0
  65. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/parsing.py +0 -0
  66. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/preprocessors.py +0 -0
  67. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/response_selection.py +0 -0
  68. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/search.py +0 -0
  69. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/storage/__init__.py +0 -0
  70. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/storage/django_storage.py +0 -0
  71. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/storage/mongodb.py +0 -0
  72. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/storage/redis.py +0 -0
  73. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/storage/sql_storage.py +0 -0
  74. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/storage/storage_adapter.py +0 -0
  75. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/tagging.py +0 -0
  76. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/utils.py +0 -0
  77. {chatterbot-1.2.15 → chatterbot-1.2.17}/chatterbot/vectorstores.py +0 -0
  78. {chatterbot-1.2.15 → chatterbot-1.2.17}/setup.cfg +0 -0
  79. {chatterbot-1.2.15 → chatterbot-1.2.17}/tests/test_adapter_validation.py +0 -0
  80. {chatterbot-1.2.15 → chatterbot-1.2.17}/tests/test_benchmarks.py +0 -0
  81. {chatterbot-1.2.15 → chatterbot-1.2.17}/tests/test_cli.py +0 -0
  82. {chatterbot-1.2.15 → chatterbot-1.2.17}/tests/test_comparisons.py +0 -0
  83. {chatterbot-1.2.15 → chatterbot-1.2.17}/tests/test_conversations.py +0 -0
  84. {chatterbot-1.2.15 → chatterbot-1.2.17}/tests/test_corpus.py +0 -0
  85. {chatterbot-1.2.15 → chatterbot-1.2.17}/tests/test_examples.py +0 -0
  86. {chatterbot-1.2.15 → chatterbot-1.2.17}/tests/test_filters.py +0 -0
  87. {chatterbot-1.2.15 → chatterbot-1.2.17}/tests/test_initialization.py +0 -0
  88. {chatterbot-1.2.15 → chatterbot-1.2.17}/tests/test_languages.py +0 -0
  89. {chatterbot-1.2.15 → chatterbot-1.2.17}/tests/test_parsing.py +0 -0
  90. {chatterbot-1.2.15 → chatterbot-1.2.17}/tests/test_preprocessors.py +0 -0
  91. {chatterbot-1.2.15 → chatterbot-1.2.17}/tests/test_response_selection.py +0 -0
  92. {chatterbot-1.2.15 → chatterbot-1.2.17}/tests/test_search.py +0 -0
  93. {chatterbot-1.2.15 → chatterbot-1.2.17}/tests/test_tagging.py +0 -0
  94. {chatterbot-1.2.15 → chatterbot-1.2.17}/tests/test_turing.py +0 -0
  95. {chatterbot-1.2.15 → chatterbot-1.2.17}/tests/test_utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ChatterBot
3
- Version: 1.2.15
3
+ Version: 1.2.17
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,>=4.1; extra == "test"
45
+ Requires-Dist: django<6.0,>=5.2.15; 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"
@@ -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,>=4.1
30
+ django<6.0,>=5.2.15
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ChatterBot
3
- Version: 1.2.15
3
+ Version: 1.2.17
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,>=4.1; extra == "test"
45
+ Requires-Dist: django<6.0,>=5.2.15; 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"
@@ -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.15'
7
+ __version__ = '1.2.17'
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)
@@ -332,6 +343,17 @@ class ChatBot(object):
332
343
  if most_common.count > 1:
333
344
  result = most_common.statement
334
345
 
346
+ if result is None:
347
+ raise self.ChatBotException(
348
+ f'No logic adapter was able to process the statement "{input_statement.text}".'
349
+ )
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
+
335
357
  response = Statement(
336
358
  text=result.text,
337
359
  in_response_to=input_statement.text,
@@ -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
 
@@ -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(
@@ -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
 
@@ -117,8 +117,10 @@ class UnitConversion(LogicAdapter, MCPToolAdapter):
117
117
  """
118
118
  response = Statement(text='')
119
119
 
120
- from_parsed = match.group("from")
121
- target_parsed = match.group("target")
120
+ # Units are captured as any non-whitespace text, so a question such
121
+ # as "How many meters are in one kilometer?" captures "kilometer?"
122
+ from_parsed = match.group("from").rstrip('?!.,;:')
123
+ target_parsed = match.group("target").rstrip('?!.,;:')
122
124
  n_statement = match.group("number")
123
125
 
124
126
  if n_statement == 'a' or n_statement == 'an':
@@ -26,6 +26,16 @@ _DIR_FD_EXTRACTION_SUPPORTED = (
26
26
  and os.path.isdir('/proc/self/fd')
27
27
  )
28
28
 
29
+ # The download path opens the archive itself rather than handing a path to
30
+ # tarfile, so it needs no procfs magic path and can be anchored to a directory
31
+ # fd anywhere the relevant calls accept one.
32
+ _DIR_FD_DOWNLOAD_SUPPORTED = (
33
+ hasattr(os, 'O_NOFOLLOW')
34
+ and os.open in os.supports_dir_fd
35
+ and os.rename in os.supports_dir_fd
36
+ and os.unlink in os.supports_dir_fd
37
+ )
38
+
29
39
 
30
40
  class Trainer(object):
31
41
  """
@@ -609,28 +619,77 @@ class UbuntuCorpusTrainer(CsvFileTrainer):
609
619
  file_name = url.split('/')[-1]
610
620
  file_path = os.path.join(self.data_directory, file_name)
611
621
 
622
+ self._reject_symlinked_path(file_path)
623
+
612
624
  # Do not download the data if it already exists
613
625
  if self.is_downloaded(file_path):
614
626
  return file_path
615
627
 
616
- with open(file_path, 'wb') as open_file:
617
- if show_status:
618
- print('Downloading %s' % url)
619
- response = requests.get(url, stream=True)
620
- total_length = response.headers.get('content-length')
621
-
622
- if total_length is None:
623
- # No content length header. Stream regardless of whether
624
- # progress is shown, to avoid buffering the whole body in memory.
625
- for data in response.iter_content(chunk_size=4096):
626
- open_file.write(data)
628
+ # Write to an unpredictably-named staging file and commit it with a
629
+ # rename, the same way extract() stages its output. os.rename()
630
+ # replaces a symlink at the destination instead of writing through it,
631
+ # so the archive lands inside data_directory even if the path is
632
+ # swapped after the check above. Where supported, the open, the rename
633
+ # and the cleanup are all anchored to a directory fd held open with
634
+ # O_NOFOLLOW, which keeps them bound to the directory inode verified
635
+ # here rather than to whatever the path resolves to later on.
636
+ base_fd = None
637
+ if _DIR_FD_DOWNLOAD_SUPPORTED:
638
+ base_fd = self._open_verified_directory_fd(self.data_directory)
639
+
640
+ staging_name = 'tmp_' + secrets.token_hex(8)
641
+ staging_path = os.path.join(self.data_directory, staging_name)
642
+ open_flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
643
+ # O_NOFOLLOW is POSIX-only, and O_BINARY exists only on Windows, where
644
+ # os.open() would otherwise translate newlines inside the archive.
645
+ open_flags |= getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_BINARY', 0)
646
+
647
+ try:
648
+ if base_fd is not None:
649
+ staging_fd = os.open(staging_name, open_flags, 0o666, dir_fd=base_fd)
627
650
  else:
628
- for data in tqdm(
629
- response.iter_content(chunk_size=4096),
630
- desc='Downloading',
631
- disable=not show_status
632
- ):
633
- open_file.write(data)
651
+ staging_fd = os.open(staging_path, open_flags, 0o666)
652
+
653
+ with os.fdopen(staging_fd, 'wb') as open_file:
654
+ if show_status:
655
+ print('Downloading %s' % url)
656
+ response = requests.get(url, stream=True)
657
+ total_length = response.headers.get('content-length')
658
+
659
+ if total_length is None:
660
+ # No content length header. Stream regardless of whether
661
+ # progress is shown, to avoid buffering the whole body in memory.
662
+ for data in response.iter_content(chunk_size=4096):
663
+ open_file.write(data)
664
+ else:
665
+ for data in tqdm(
666
+ response.iter_content(chunk_size=4096),
667
+ desc='Downloading',
668
+ disable=not show_status
669
+ ):
670
+ open_file.write(data)
671
+
672
+ try:
673
+ if base_fd is not None:
674
+ os.rename(staging_name, file_name, src_dir_fd=base_fd, dst_dir_fd=base_fd)
675
+ else:
676
+ os.rename(staging_path, file_path)
677
+ except OSError as e:
678
+ raise self.TrainerInitializationException(
679
+ 'Refusing to commit downloaded archive to {}: {}'.format(file_path, e)
680
+ ) from e
681
+ except BaseException:
682
+ try:
683
+ if base_fd is not None:
684
+ os.unlink(staging_name, dir_fd=base_fd)
685
+ else:
686
+ os.unlink(staging_path)
687
+ except OSError:
688
+ pass
689
+ raise
690
+ finally:
691
+ if base_fd is not None:
692
+ os.close(base_fd)
634
693
 
635
694
  if show_status:
636
695
  print('Download location: %s' % file_path)
@@ -656,7 +715,7 @@ class UbuntuCorpusTrainer(CsvFileTrainer):
656
715
  return os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
657
716
  except OSError as e:
658
717
  raise self.TrainerInitializationException(
659
- 'Refusing to extract archive: unable to safely open {}: {}'.format(path, e)
718
+ 'Refusing to use data directory: unable to safely open {}: {}'.format(path, e)
660
719
  ) from e
661
720
 
662
721
  def extract(self, file_path: str):
@@ -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>=4.1,<6.0"
77
+ "django>=5.2.15,<6.0"
78
78
  ]
79
79
  dev = [
80
80
  "pint>=0.8.1",
@@ -1,8 +1,10 @@
1
1
  from tests.base_case import ChatBotTestCase
2
2
  from chatterbot import ChatBot
3
- from chatterbot.logic import LogicAdapter
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
 
@@ -401,6 +426,77 @@ class TestAdapterC(LogicAdapter):
401
426
 
402
427
  class ChatBotLogicAdapterTestCase(ChatBotTestCase):
403
428
 
429
+ def test_adapter_comparison_functions_are_isolated(self):
430
+ self.chatbot.logic_adapters = [
431
+ utils.initialize_class(
432
+ {
433
+ 'import_path': 'chatterbot.logic.BestMatch',
434
+ 'statement_comparison_function': 'chatterbot.comparisons.JaccardSimilarity'
435
+ },
436
+ self.chatbot
437
+ ),
438
+ BestMatch(
439
+ self.chatbot,
440
+ statement_comparison_function=comparisons.LevenshteinDistance
441
+ )
442
+ ]
443
+
444
+ self.assertIsInstance(
445
+ self.chatbot.logic_adapters[0].search_algorithm.compare_statements,
446
+ comparisons.JaccardSimilarity
447
+ )
448
+ self.assertIsInstance(
449
+ self.chatbot.logic_adapters[1].search_algorithm.compare_statements,
450
+ comparisons.LevenshteinDistance
451
+ )
452
+ self.assertIsNot(
453
+ self.chatbot.logic_adapters[0].search_algorithm,
454
+ self.chatbot.logic_adapters[1].search_algorithm
455
+ )
456
+ self.assertIsInstance(
457
+ self.chatbot.search_algorithms['indexed_text_search'].compare_statements,
458
+ comparisons.LevenshteinDistance
459
+ )
460
+ self.assertEqual(self.chatbot.logic_adapters[0].maximum_similarity_threshold, 0.5)
461
+ self.assertEqual(self.chatbot.logic_adapters[1].maximum_similarity_threshold, 0.7)
462
+
463
+ spacy_adapter = BestMatch(
464
+ self.chatbot,
465
+ statement_comparison_function=comparisons.SpacySimilarity
466
+ )
467
+ self.assertEqual(spacy_adapter.maximum_similarity_threshold, 0.7)
468
+
469
+ overridden_adapter = BestMatch(
470
+ self.chatbot,
471
+ statement_comparison_function=comparisons.LevenshteinDistance,
472
+ maximum_similarity_threshold=0.6
473
+ )
474
+ self.assertEqual(overridden_adapter.maximum_similarity_threshold, 0.6)
475
+
476
+ def test_single_word_query_uses_comparer_default_confidence(self):
477
+ question = 'What is a microprocessor?'
478
+ answer = 'An integrated circuit that implements the functions of a central processing unit of a computer.'
479
+ self._create_with_search_text(text=question)
480
+ self._create_with_search_text(text=answer, in_response_to=question)
481
+
482
+ for comparison_function in (
483
+ comparisons.JaccardSimilarity,
484
+ comparisons.LevenshteinDistance
485
+ ):
486
+ self.chatbot.logic_adapters = [
487
+ BestMatch(
488
+ self.chatbot,
489
+ statement_comparison_function=comparison_function,
490
+ default_response='I do not understand.'
491
+ )
492
+ ]
493
+
494
+ response = self.chatbot.generate_response(
495
+ self._add_search_text(text='microprocessor')
496
+ )
497
+
498
+ self.assertEqual(response.text, answer)
499
+
404
500
  def test_sub_adapter_agreement(self):
405
501
  """
406
502
  In the case that multiple adapters agree on a given
@@ -418,6 +514,32 @@ class ChatBotLogicAdapterTestCase(ChatBotTestCase):
418
514
  self.assertEqual(statement.confidence, 0.5)
419
515
  self.assertEqual(statement.text, 'Good morning.')
420
516
 
517
+ def test_default_response_when_no_adapter_meets_similarity_threshold(self):
518
+ self.chatbot.logic_adapters = [
519
+ TestAdapterA(
520
+ self.chatbot,
521
+ default_response='I do not understand.',
522
+ maximum_similarity_threshold=0.65
523
+ )
524
+ ]
525
+
526
+ response = self.chatbot.generate_response(Statement(text='Something unexpected'))
527
+
528
+ self.assertEqual(response.text, 'I do not understand.')
529
+ self.assertEqual(response.confidence, 0)
530
+
531
+ def test_no_adapter_can_process_statement(self):
532
+ """
533
+ If no logic adapter can process the statement,
534
+ a ChatBotException should be raised.
535
+ """
536
+ self.chatbot.logic_adapters = [MathematicalEvaluation(self.chatbot)]
537
+
538
+ with self.assertRaises(ChatBot.ChatBotException) as exc:
539
+ self.chatbot.generate_response(Statement(text='Howdy!'))
540
+
541
+ self.assertIn('No logic adapter was able to process', str(exc.exception))
542
+
421
543
  def test_chatbot_set_for_all_logic_adapters(self):
422
544
  for sub_adapter in self.chatbot.logic_adapters:
423
545
  self.assertEqual(sub_adapter.chatbot, self.chatbot)
File without changes
File without changes
File without changes