spark-nlp 4.2.6__py2.py3-none-any.whl → 6.2.1__py2.py3-none-any.whl

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 (221) hide show
  1. com/johnsnowlabs/ml/__init__.py +0 -0
  2. com/johnsnowlabs/ml/ai/__init__.py +10 -0
  3. spark_nlp-6.2.1.dist-info/METADATA +362 -0
  4. spark_nlp-6.2.1.dist-info/RECORD +292 -0
  5. {spark_nlp-4.2.6.dist-info → spark_nlp-6.2.1.dist-info}/WHEEL +1 -1
  6. sparknlp/__init__.py +81 -28
  7. sparknlp/annotation.py +3 -2
  8. sparknlp/annotator/__init__.py +6 -0
  9. sparknlp/annotator/audio/__init__.py +2 -0
  10. sparknlp/annotator/audio/hubert_for_ctc.py +188 -0
  11. sparknlp/annotator/audio/wav2vec2_for_ctc.py +14 -14
  12. sparknlp/annotator/audio/whisper_for_ctc.py +251 -0
  13. sparknlp/{base → annotator}/chunk2_doc.py +4 -7
  14. sparknlp/annotator/chunker.py +1 -2
  15. sparknlp/annotator/classifier_dl/__init__.py +17 -0
  16. sparknlp/annotator/classifier_dl/albert_for_multiple_choice.py +161 -0
  17. sparknlp/annotator/classifier_dl/albert_for_question_answering.py +3 -15
  18. sparknlp/annotator/classifier_dl/albert_for_sequence_classification.py +4 -18
  19. sparknlp/annotator/classifier_dl/albert_for_token_classification.py +3 -17
  20. sparknlp/annotator/classifier_dl/albert_for_zero_shot_classification.py +211 -0
  21. sparknlp/annotator/classifier_dl/bart_for_zero_shot_classification.py +225 -0
  22. sparknlp/annotator/classifier_dl/bert_for_multiple_choice.py +161 -0
  23. sparknlp/annotator/classifier_dl/bert_for_question_answering.py +6 -20
  24. sparknlp/annotator/classifier_dl/bert_for_sequence_classification.py +3 -17
  25. sparknlp/annotator/classifier_dl/bert_for_token_classification.py +3 -17
  26. sparknlp/annotator/classifier_dl/bert_for_zero_shot_classification.py +212 -0
  27. sparknlp/annotator/classifier_dl/camembert_for_question_answering.py +168 -0
  28. sparknlp/annotator/classifier_dl/camembert_for_sequence_classification.py +5 -19
  29. sparknlp/annotator/classifier_dl/camembert_for_token_classification.py +5 -19
  30. sparknlp/annotator/classifier_dl/camembert_for_zero_shot_classification.py +202 -0
  31. sparknlp/annotator/classifier_dl/classifier_dl.py +4 -4
  32. sparknlp/annotator/classifier_dl/deberta_for_question_answering.py +3 -17
  33. sparknlp/annotator/classifier_dl/deberta_for_sequence_classification.py +4 -19
  34. sparknlp/annotator/classifier_dl/deberta_for_token_classification.py +5 -21
  35. sparknlp/annotator/classifier_dl/deberta_for_zero_shot_classification.py +193 -0
  36. sparknlp/annotator/classifier_dl/distil_bert_for_question_answering.py +3 -17
  37. sparknlp/annotator/classifier_dl/distil_bert_for_sequence_classification.py +4 -18
  38. sparknlp/annotator/classifier_dl/distil_bert_for_token_classification.py +3 -17
  39. sparknlp/annotator/classifier_dl/distil_bert_for_zero_shot_classification.py +211 -0
  40. sparknlp/annotator/classifier_dl/distilbert_for_multiple_choice.py +161 -0
  41. sparknlp/annotator/classifier_dl/longformer_for_question_answering.py +3 -17
  42. sparknlp/annotator/classifier_dl/longformer_for_sequence_classification.py +4 -18
  43. sparknlp/annotator/classifier_dl/longformer_for_token_classification.py +3 -17
  44. sparknlp/annotator/classifier_dl/mpnet_for_question_answering.py +148 -0
  45. sparknlp/annotator/classifier_dl/mpnet_for_sequence_classification.py +188 -0
  46. sparknlp/annotator/classifier_dl/mpnet_for_token_classification.py +173 -0
  47. sparknlp/annotator/classifier_dl/multi_classifier_dl.py +3 -3
  48. sparknlp/annotator/classifier_dl/roberta_for_multiple_choice.py +161 -0
  49. sparknlp/annotator/classifier_dl/roberta_for_question_answering.py +3 -17
  50. sparknlp/annotator/classifier_dl/roberta_for_sequence_classification.py +4 -18
  51. sparknlp/annotator/classifier_dl/roberta_for_token_classification.py +1 -1
  52. sparknlp/annotator/classifier_dl/roberta_for_zero_shot_classification.py +225 -0
  53. sparknlp/annotator/classifier_dl/sentiment_dl.py +4 -4
  54. sparknlp/annotator/classifier_dl/tapas_for_question_answering.py +2 -2
  55. sparknlp/annotator/classifier_dl/xlm_roberta_for_multiple_choice.py +149 -0
  56. sparknlp/annotator/classifier_dl/xlm_roberta_for_question_answering.py +3 -17
  57. sparknlp/annotator/classifier_dl/xlm_roberta_for_sequence_classification.py +4 -18
  58. sparknlp/annotator/classifier_dl/xlm_roberta_for_token_classification.py +6 -20
  59. sparknlp/annotator/classifier_dl/xlm_roberta_for_zero_shot_classification.py +225 -0
  60. sparknlp/annotator/classifier_dl/xlnet_for_sequence_classification.py +4 -18
  61. sparknlp/annotator/classifier_dl/xlnet_for_token_classification.py +3 -17
  62. sparknlp/annotator/cleaners/__init__.py +15 -0
  63. sparknlp/annotator/cleaners/cleaner.py +202 -0
  64. sparknlp/annotator/cleaners/extractor.py +191 -0
  65. sparknlp/annotator/coref/spanbert_coref.py +4 -18
  66. sparknlp/annotator/cv/__init__.py +15 -0
  67. sparknlp/annotator/cv/blip_for_question_answering.py +172 -0
  68. sparknlp/annotator/cv/clip_for_zero_shot_classification.py +193 -0
  69. sparknlp/annotator/cv/convnext_for_image_classification.py +269 -0
  70. sparknlp/annotator/cv/florence2_transformer.py +180 -0
  71. sparknlp/annotator/cv/gemma3_for_multimodal.py +346 -0
  72. sparknlp/annotator/cv/internvl_for_multimodal.py +280 -0
  73. sparknlp/annotator/cv/janus_for_multimodal.py +351 -0
  74. sparknlp/annotator/cv/llava_for_multimodal.py +328 -0
  75. sparknlp/annotator/cv/mllama_for_multimodal.py +340 -0
  76. sparknlp/annotator/cv/paligemma_for_multimodal.py +308 -0
  77. sparknlp/annotator/cv/phi3_vision_for_multimodal.py +328 -0
  78. sparknlp/annotator/cv/qwen2vl_transformer.py +332 -0
  79. sparknlp/annotator/cv/smolvlm_transformer.py +426 -0
  80. sparknlp/annotator/cv/swin_for_image_classification.py +242 -0
  81. sparknlp/annotator/cv/vision_encoder_decoder_for_image_captioning.py +240 -0
  82. sparknlp/annotator/cv/vit_for_image_classification.py +36 -4
  83. sparknlp/annotator/dataframe_optimizer.py +216 -0
  84. sparknlp/annotator/date2_chunk.py +88 -0
  85. sparknlp/annotator/dependency/dependency_parser.py +2 -3
  86. sparknlp/annotator/dependency/typed_dependency_parser.py +3 -4
  87. sparknlp/annotator/document_character_text_splitter.py +228 -0
  88. sparknlp/annotator/document_normalizer.py +37 -1
  89. sparknlp/annotator/document_token_splitter.py +175 -0
  90. sparknlp/annotator/document_token_splitter_test.py +85 -0
  91. sparknlp/annotator/embeddings/__init__.py +11 -0
  92. sparknlp/annotator/embeddings/albert_embeddings.py +4 -18
  93. sparknlp/annotator/embeddings/auto_gguf_embeddings.py +539 -0
  94. sparknlp/annotator/embeddings/bert_embeddings.py +9 -22
  95. sparknlp/annotator/embeddings/bert_sentence_embeddings.py +12 -24
  96. sparknlp/annotator/embeddings/bge_embeddings.py +199 -0
  97. sparknlp/annotator/embeddings/camembert_embeddings.py +4 -20
  98. sparknlp/annotator/embeddings/chunk_embeddings.py +1 -2
  99. sparknlp/annotator/embeddings/deberta_embeddings.py +2 -16
  100. sparknlp/annotator/embeddings/distil_bert_embeddings.py +5 -19
  101. sparknlp/annotator/embeddings/doc2vec.py +7 -1
  102. sparknlp/annotator/embeddings/e5_embeddings.py +195 -0
  103. sparknlp/annotator/embeddings/e5v_embeddings.py +138 -0
  104. sparknlp/annotator/embeddings/elmo_embeddings.py +2 -2
  105. sparknlp/annotator/embeddings/instructor_embeddings.py +204 -0
  106. sparknlp/annotator/embeddings/longformer_embeddings.py +3 -17
  107. sparknlp/annotator/embeddings/minilm_embeddings.py +189 -0
  108. sparknlp/annotator/embeddings/mpnet_embeddings.py +192 -0
  109. sparknlp/annotator/embeddings/mxbai_embeddings.py +184 -0
  110. sparknlp/annotator/embeddings/nomic_embeddings.py +181 -0
  111. sparknlp/annotator/embeddings/roberta_embeddings.py +9 -21
  112. sparknlp/annotator/embeddings/roberta_sentence_embeddings.py +7 -21
  113. sparknlp/annotator/embeddings/sentence_embeddings.py +2 -3
  114. sparknlp/annotator/embeddings/snowflake_embeddings.py +202 -0
  115. sparknlp/annotator/embeddings/uae_embeddings.py +211 -0
  116. sparknlp/annotator/embeddings/universal_sentence_encoder.py +3 -3
  117. sparknlp/annotator/embeddings/word2vec.py +7 -1
  118. sparknlp/annotator/embeddings/word_embeddings.py +4 -5
  119. sparknlp/annotator/embeddings/xlm_roberta_embeddings.py +9 -21
  120. sparknlp/annotator/embeddings/xlm_roberta_sentence_embeddings.py +7 -21
  121. sparknlp/annotator/embeddings/xlnet_embeddings.py +4 -18
  122. sparknlp/annotator/er/entity_ruler.py +37 -23
  123. sparknlp/annotator/keyword_extraction/yake_keyword_extraction.py +2 -3
  124. sparknlp/annotator/ld_dl/language_detector_dl.py +2 -2
  125. sparknlp/annotator/lemmatizer.py +3 -4
  126. sparknlp/annotator/matcher/date_matcher.py +35 -3
  127. sparknlp/annotator/matcher/multi_date_matcher.py +1 -2
  128. sparknlp/annotator/matcher/regex_matcher.py +3 -3
  129. sparknlp/annotator/matcher/text_matcher.py +2 -3
  130. sparknlp/annotator/n_gram_generator.py +1 -2
  131. sparknlp/annotator/ner/__init__.py +3 -1
  132. sparknlp/annotator/ner/ner_converter.py +18 -0
  133. sparknlp/annotator/ner/ner_crf.py +4 -5
  134. sparknlp/annotator/ner/ner_dl.py +10 -5
  135. sparknlp/annotator/ner/ner_dl_graph_checker.py +293 -0
  136. sparknlp/annotator/ner/ner_overwriter.py +2 -2
  137. sparknlp/annotator/ner/zero_shot_ner_model.py +173 -0
  138. sparknlp/annotator/normalizer.py +2 -2
  139. sparknlp/annotator/openai/__init__.py +16 -0
  140. sparknlp/annotator/openai/openai_completion.py +349 -0
  141. sparknlp/annotator/openai/openai_embeddings.py +106 -0
  142. sparknlp/annotator/pos/perceptron.py +6 -7
  143. sparknlp/annotator/sentence/sentence_detector.py +2 -2
  144. sparknlp/annotator/sentence/sentence_detector_dl.py +3 -3
  145. sparknlp/annotator/sentiment/sentiment_detector.py +4 -5
  146. sparknlp/annotator/sentiment/vivekn_sentiment.py +4 -5
  147. sparknlp/annotator/seq2seq/__init__.py +17 -0
  148. sparknlp/annotator/seq2seq/auto_gguf_model.py +304 -0
  149. sparknlp/annotator/seq2seq/auto_gguf_reranker.py +334 -0
  150. sparknlp/annotator/seq2seq/auto_gguf_vision_model.py +336 -0
  151. sparknlp/annotator/seq2seq/bart_transformer.py +420 -0
  152. sparknlp/annotator/seq2seq/cohere_transformer.py +357 -0
  153. sparknlp/annotator/seq2seq/cpm_transformer.py +321 -0
  154. sparknlp/annotator/seq2seq/gpt2_transformer.py +1 -1
  155. sparknlp/annotator/seq2seq/llama2_transformer.py +343 -0
  156. sparknlp/annotator/seq2seq/llama3_transformer.py +381 -0
  157. sparknlp/annotator/seq2seq/m2m100_transformer.py +392 -0
  158. sparknlp/annotator/seq2seq/marian_transformer.py +124 -3
  159. sparknlp/annotator/seq2seq/mistral_transformer.py +348 -0
  160. sparknlp/annotator/seq2seq/nllb_transformer.py +420 -0
  161. sparknlp/annotator/seq2seq/olmo_transformer.py +326 -0
  162. sparknlp/annotator/seq2seq/phi2_transformer.py +326 -0
  163. sparknlp/annotator/seq2seq/phi3_transformer.py +330 -0
  164. sparknlp/annotator/seq2seq/phi4_transformer.py +387 -0
  165. sparknlp/annotator/seq2seq/qwen_transformer.py +340 -0
  166. sparknlp/annotator/seq2seq/starcoder_transformer.py +335 -0
  167. sparknlp/annotator/seq2seq/t5_transformer.py +54 -4
  168. sparknlp/annotator/similarity/__init__.py +0 -0
  169. sparknlp/annotator/similarity/document_similarity_ranker.py +379 -0
  170. sparknlp/annotator/spell_check/context_spell_checker.py +116 -17
  171. sparknlp/annotator/spell_check/norvig_sweeting.py +3 -6
  172. sparknlp/annotator/spell_check/symmetric_delete.py +1 -1
  173. sparknlp/annotator/stemmer.py +2 -3
  174. sparknlp/annotator/stop_words_cleaner.py +3 -4
  175. sparknlp/annotator/tf_ner_dl_graph_builder.py +1 -1
  176. sparknlp/annotator/token/__init__.py +0 -1
  177. sparknlp/annotator/token/recursive_tokenizer.py +2 -3
  178. sparknlp/annotator/token/tokenizer.py +2 -3
  179. sparknlp/annotator/ws/word_segmenter.py +35 -10
  180. sparknlp/base/__init__.py +2 -3
  181. sparknlp/base/doc2_chunk.py +0 -3
  182. sparknlp/base/document_assembler.py +5 -5
  183. sparknlp/base/embeddings_finisher.py +14 -2
  184. sparknlp/base/finisher.py +15 -4
  185. sparknlp/base/gguf_ranking_finisher.py +234 -0
  186. sparknlp/base/image_assembler.py +69 -0
  187. sparknlp/base/light_pipeline.py +53 -21
  188. sparknlp/base/multi_document_assembler.py +9 -13
  189. sparknlp/base/prompt_assembler.py +207 -0
  190. sparknlp/base/token_assembler.py +1 -2
  191. sparknlp/common/__init__.py +2 -0
  192. sparknlp/common/annotator_type.py +1 -0
  193. sparknlp/common/completion_post_processing.py +37 -0
  194. sparknlp/common/match_strategy.py +33 -0
  195. sparknlp/common/properties.py +914 -9
  196. sparknlp/internal/__init__.py +841 -116
  197. sparknlp/internal/annotator_java_ml.py +1 -1
  198. sparknlp/internal/annotator_transformer.py +3 -0
  199. sparknlp/logging/comet.py +2 -2
  200. sparknlp/partition/__init__.py +16 -0
  201. sparknlp/partition/partition.py +244 -0
  202. sparknlp/partition/partition_properties.py +902 -0
  203. sparknlp/partition/partition_transformer.py +200 -0
  204. sparknlp/pretrained/pretrained_pipeline.py +1 -1
  205. sparknlp/pretrained/resource_downloader.py +126 -2
  206. sparknlp/reader/__init__.py +15 -0
  207. sparknlp/reader/enums.py +19 -0
  208. sparknlp/reader/pdf_to_text.py +190 -0
  209. sparknlp/reader/reader2doc.py +124 -0
  210. sparknlp/reader/reader2image.py +136 -0
  211. sparknlp/reader/reader2table.py +44 -0
  212. sparknlp/reader/reader_assembler.py +159 -0
  213. sparknlp/reader/sparknlp_reader.py +461 -0
  214. sparknlp/training/__init__.py +1 -0
  215. sparknlp/training/conll.py +8 -2
  216. sparknlp/training/spacy_to_annotation.py +57 -0
  217. sparknlp/util.py +26 -0
  218. spark_nlp-4.2.6.dist-info/METADATA +0 -1256
  219. spark_nlp-4.2.6.dist-info/RECORD +0 -196
  220. {spark_nlp-4.2.6.dist-info → spark_nlp-6.2.1.dist-info}/top_level.txt +0 -0
  221. /sparknlp/annotator/{token/token2_chunk.py → token2_chunk.py} +0 -0
@@ -12,14 +12,13 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
  """Contains classes for the LightPipeline."""
15
- from sparknlp.base.multi_document_assembler import MultiDocumentAssembler
16
15
 
17
16
  import sparknlp.internal as _internal
18
-
19
17
  from sparknlp.annotation import Annotation
20
18
  from sparknlp.annotation_audio import AnnotationAudio
21
19
  from sparknlp.annotation_image import AnnotationImage
22
20
  from sparknlp.common import AnnotatorApproach, AnnotatorModel
21
+ from sparknlp.internal import AnnotatorTransformer
23
22
 
24
23
 
25
24
  class LightPipeline:
@@ -66,17 +65,17 @@ class LightPipeline:
66
65
 
67
66
  def __init__(self, pipelineModel, parse_embeddings=False):
68
67
  self.pipeline_model = pipelineModel
68
+ self.parse_embeddings = parse_embeddings
69
69
  self._lightPipeline = _internal._LightPipeline(pipelineModel, parse_embeddings).apply()
70
70
 
71
- def _validateStagesInputCols(self):
72
- stages = self.pipeline_model.stages
71
+ def _validateStagesInputCols(self, stages):
73
72
  annotator_types = self._getAnnotatorTypes(stages)
74
73
  for stage in stages:
75
74
  if isinstance(stage, AnnotatorApproach) or isinstance(stage, AnnotatorModel):
76
75
  input_cols = stage.getInputCols()
77
76
  if type(input_cols) == str:
78
77
  input_cols = [input_cols]
79
- input_annotator_types = stage.inputAnnotatorTypes
78
+ input_annotator_types = stage.inputAnnotatorTypes + stage.optionalInputAnnotatorTypes
80
79
  for input_col in input_cols:
81
80
  annotator_type = annotator_types.get(input_col)
82
81
  if annotator_type is None or annotator_type not in input_annotator_types:
@@ -85,15 +84,27 @@ class LightPipeline:
85
84
  f" with the right output names and that they have following annotator types:"
86
85
  f" {input_annotator_types}")
87
86
 
87
+ def _skipPipelineValidation(self, stages):
88
+ exceptional_pipeline = [stage for stage in stages if self._skipStageValidation(stage)]
89
+ if len(exceptional_pipeline) >= 1:
90
+ return True
91
+ else:
92
+ return False
93
+
94
+ def _skipStageValidation(self, stage):
95
+ return hasattr(stage, 'skipLPInputColsValidation') and stage.skipLPInputColsValidation
96
+
88
97
  def _getAnnotatorTypes(self, stages):
89
98
  annotator_types = {}
90
99
  for stage in stages:
91
- if isinstance(stage, MultiDocumentAssembler):
100
+ if hasattr(stage, 'getOutputCols'):
92
101
  output_cols = stage.getOutputCols()
93
102
  for output_col in output_cols:
94
103
  annotator_types[output_col] = stage.outputAnnotatorType
95
- else:
96
- annotator_types[stage.getOutputCol()] = stage.outputAnnotatorType
104
+ elif isinstance(stage, AnnotatorApproach) or isinstance(stage, AnnotatorModel) or\
105
+ isinstance(stage, AnnotatorTransformer):
106
+ if stage.outputAnnotatorType is not None:
107
+ annotator_types[stage.getOutputCol()] = stage.outputAnnotatorType
97
108
  return annotator_types
98
109
 
99
110
  def _annotationFromJava(self, java_annotations):
@@ -123,13 +134,17 @@ class LightPipeline:
123
134
  annotation.metadata())
124
135
  )
125
136
  else:
137
+ if self.parse_embeddings:
138
+ embeddings = list(annotation.embeddings())
139
+ else:
140
+ embeddings = []
126
141
  annotations.append(
127
142
  Annotation(annotation.annotatorType(),
128
143
  annotation.begin(),
129
144
  annotation.end(),
130
145
  annotation.result(),
131
146
  annotation.metadata(),
132
- [])
147
+ embeddings)
133
148
  )
134
149
  return annotations
135
150
 
@@ -176,7 +191,9 @@ class LightPipeline:
176
191
  Annotation(named_entity, 30, 36, B-LOC, {'word': 'Baghdad'}),
177
192
  Annotation(named_entity, 37, 37, O, {'word': '.'})]
178
193
  """
179
- self._validateStagesInputCols()
194
+ stages = self.pipeline_model.stages
195
+ if not self._skipPipelineValidation(stages):
196
+ self._validateStagesInputCols(stages)
180
197
 
181
198
  if optional_target == "":
182
199
  if self.__isTextInput(target):
@@ -260,7 +277,7 @@ class LightPipeline:
260
277
 
261
278
  return result
262
279
 
263
- def fullAnnotateImage(self, path_to_image):
280
+ def fullAnnotateImage(self, path_to_image, text=None):
264
281
  """Annotates the data provided into `Annotation` type results.
265
282
 
266
283
  The data should be either a list or a str.
@@ -270,25 +287,38 @@ class LightPipeline:
270
287
  path_to_image : list or str
271
288
  Source path of image, list of paths to images
272
289
 
290
+ text: list or str, optional
291
+ Optional list or str of texts. If None, defaults to empty list if path_to_image is a list, or empty string if path_to_image is a string.
292
+
273
293
  Returns
274
294
  -------
275
295
  List[AnnotationImage]
276
296
  The result of the annotation
277
297
  """
278
- self._validateStagesInputCols()
298
+ if not isinstance(path_to_image, (str, list)):
299
+ raise TypeError("argument for path_to_image must be 'str' or 'list[str]'")
300
+
301
+ if text is None:
302
+ text = "" if isinstance(path_to_image, str) else []
279
303
 
280
- if type(path_to_image) is str:
304
+ if type(path_to_image) != type(text):
305
+ raise ValueError("`path_to_image` and `text` must be of the same type")
306
+
307
+ stages = self.pipeline_model.stages
308
+ if not self._skipPipelineValidation(stages):
309
+ self._validateStagesInputCols(stages)
310
+
311
+ if isinstance(path_to_image, str):
281
312
  path_to_image = [path_to_image]
313
+ text = [text]
282
314
 
283
- if type(path_to_image) is list:
284
- result = []
315
+ result = []
285
316
 
286
- for image_result in self._lightPipeline.fullAnnotateImageJava(path_to_image):
287
- result.append(self.__buildStages(image_result))
317
+ for image_result in self._lightPipeline.fullAnnotateImageJava(path_to_image, text):
318
+ result.append(self.__buildStages(image_result))
319
+
320
+ return result
288
321
 
289
- return result
290
- else:
291
- raise TypeError("argument for annotation may be 'str' or list[str]")
292
322
 
293
323
  def __buildStages(self, annotations_result):
294
324
  stages = {}
@@ -327,7 +357,9 @@ class LightPipeline:
327
357
  def reformat(annotations):
328
358
  return {k: list(v) for k, v in annotations.items()}
329
359
 
330
- self._validateStagesInputCols()
360
+ stages = self.pipeline_model.stages
361
+ if not self._skipPipelineValidation(stages):
362
+ self._validateStagesInputCols(stages)
331
363
 
332
364
  if optional_target == "":
333
365
  if type(target) is str:
@@ -28,7 +28,7 @@ class MultiDocumentAssembler(AnnotatorTransformer):
28
28
  refer the parameters section.
29
29
 
30
30
  For more extended examples on document pre-processing see the
31
- `Spark NLP Workshop <https://github.com/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/Certification_Trainings/Public/2.Text_Preprocessing_with_SparkNLP_Annotators_Transformers.ipynb>`__.
31
+ `Examples <https://github.com/JohnSnowLabs/spark-nlp/blob/master/examples/python/annotation/text/english/document-assembler/Loading_Multiple_Documents.ipynb>`__.
32
32
 
33
33
  ====================== ======================
34
34
  Input Annotation types Output Annotation type
@@ -38,18 +38,15 @@ class MultiDocumentAssembler(AnnotatorTransformer):
38
38
 
39
39
  Parameters
40
40
  ----------
41
- inputCols
42
- Input column name
43
- outputCols
44
- Output column name
45
- idCol
41
+ inputCols: str or List[str]
42
+ Input column name.
43
+ outputCols: str or List[str]
44
+ Output column name.
45
+ idCol: str
46
46
  Name of String type column for row id.
47
- metadataCol
47
+ metadataCol: str
48
48
  Name of Map type column with metadata information
49
- calculationsCol
50
- Name of float vector map column to use for embeddings and other
51
- representations.
52
- cleanupMode
49
+ cleanupMode: str
53
50
  How to cleanup the document , by default disabled.
54
51
  Possible values: ``disabled, inplace, inplace_full, shrink, shrink_full,
55
52
  each, each_full, delete_full``
@@ -89,7 +86,6 @@ class MultiDocumentAssembler(AnnotatorTransformer):
89
86
  outputCols = Param(Params._dummy(), "outputCols", "output finished annotation cols", typeConverter=TypeConverters.toListString)
90
87
  idCol = Param(Params._dummy(), "idCol", "column for setting an id to such string in row", typeConverter=TypeConverters.toString)
91
88
  metadataCol = Param(Params._dummy(), "metadataCol", "String to String map column to use as metadata", typeConverter=TypeConverters.toString)
92
- calculationsCol = Param(Params._dummy(), "calculationsCol", "String to Float vector map column to use as embeddigns and other representations", typeConverter=TypeConverters.toString)
93
89
  cleanupMode = Param(Params._dummy(), "cleanupMode", "possible values: disabled, inplace, inplace_full, shrink, shrink_full, each, each_full, delete_full", typeConverter=TypeConverters.toString)
94
90
  name = 'MultiDocumentAssembler'
95
91
 
@@ -108,7 +104,7 @@ class MultiDocumentAssembler(AnnotatorTransformer):
108
104
 
109
105
  Parameters
110
106
  ----------
111
- *value : str
107
+ *value : List[str]
112
108
  Input columns for the annotator
113
109
  """
114
110
  if len(value) == 1 and type(value[0]) == list:
@@ -0,0 +1,207 @@
1
+ # Copyright 2017-2024 John Snow Labs
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains classes for the PromptAssembler."""
15
+
16
+ from pyspark import keyword_only
17
+ from pyspark.ml.param import TypeConverters, Params, Param
18
+
19
+ from sparknlp.common import AnnotatorType
20
+ from sparknlp.internal import AnnotatorTransformer
21
+
22
+
23
+ class PromptAssembler(AnnotatorTransformer):
24
+ """Assembles a sequence of messages into a single string using a template. These strings can then
25
+ be used as prompts for large language models.
26
+
27
+ This annotator expects an array of two-tuples as the type of the input column (one array of
28
+ tuples per row). The first element of the tuples should be the role and the second element is
29
+ the text of the message. Possible roles are "system", "user" and "assistant".
30
+
31
+ An assistant header can be added to the end of the generated string by using
32
+ ``setAddAssistant(True)``.
33
+
34
+ At the moment, this annotator uses llama.cpp as a backend to parse and apply the templates.
35
+ llama.cpp uses basic pattern matching to determine the type of the template, then applies a
36
+ basic version of the template to the messages. This means that more advanced templates are not
37
+ supported.
38
+
39
+ For an extended example see the
40
+ `example notebook <https://github.com/JohnSnowLabs/spark-nlp/blob/master/examples/python/llama.cpp/PromptAssember_with_AutoGGUFModel.ipynb>`__.
41
+
42
+ ====================== ======================
43
+ Input Annotation types Output Annotation type
44
+ ====================== ======================
45
+ ``NONE`` ``DOCUMENT``
46
+ ====================== ======================
47
+
48
+ Parameters
49
+ ----------
50
+ inputCol
51
+ Input column name
52
+ outputCol
53
+ Output column name
54
+ chatTemplate
55
+ Template used for the chat
56
+ addAssistant
57
+ Whether to add an assistant header to the end of the generated string
58
+
59
+ Examples
60
+ --------
61
+ >>> from sparknlp.base import *
62
+ >>> messages = [
63
+ ... [
64
+ ... ("system", "You are a helpful assistant."),
65
+ ... ("assistant", "Hello there, how can I help you?"),
66
+ ... ("user", "I need help with organizing my room."),
67
+ ... ]
68
+ ... ]
69
+ >>> df = spark.createDataFrame([messages]).toDF("messages")
70
+ >>> template = (
71
+ ... "{{- bos_token }} {%- if custom_tools is defined %} {%- set tools = custom_tools %} {%- "
72
+ ... "endif %} {%- if not tools_in_user_message is defined %} {%- set tools_in_user_message = true %} {%- "
73
+ ... 'endif %} {%- if not date_string is defined %} {%- set date_string = "26 Jul 2024" %} {%- endif %} '
74
+ ... "{%- if not tools is defined %} {%- set tools = none %} {%- endif %} {#- This block extracts the "
75
+ ... "system message, so we can slot it into the right place. #} {%- if messages[0]['role'] == 'system' %}"
76
+ ... " {%- set system_message = messages[0]['content']|trim %} {%- set messages = messages[1:] %} {%- else"
77
+ ... ' %} {%- set system_message = "" %} {%- endif %} {#- System message + builtin tools #} {{- '
78
+ ... '"<|start_header_id|>system<|end_header_id|>\\n\\n" }} {%- if builtin_tools is defined or tools is '
79
+ ... 'not none %} {{- "Environment: ipython\\n" }} {%- endif %} {%- if builtin_tools is defined %} {{- '
80
+ ... '"Tools: " + builtin_tools | reject(\\'equalto\', \\'code_interpreter\\') | join(", ") + "\\n\\n"}} '
81
+ ... '{%- endif %} {{- "Cutting Knowledge Date: December 2023\\n" }} {{- "Today Date: " + date_string '
82
+ ... '+ "\\n\\n" }} {%- if tools is not none and not tools_in_user_message %} {{- "You have access to '
83
+ ... 'the following functions. To call a function, please respond with JSON for a function call." }} {{- '
84
+ ... '\\'Respond in the format {"name": function name, "parameters": dictionary of argument name and its'
85
+ ... ' value}.\\' }} {{- "Do not use variables.\\n\\n" }} {%- for t in tools %} {{- t | tojson(indent=4) '
86
+ ... '}} {{- "\\n\\n" }} {%- endfor %} {%- endif %} {{- system_message }} {{- "<|eot_id|>" }} {#- '
87
+ ... "Custom tools are passed in a user message with some extra guidance #} {%- if tools_in_user_message "
88
+ ... "and not tools is none %} {#- Extract the first user message so we can plug it in here #} {%- if "
89
+ ... "messages | length != 0 %} {%- set first_user_message = messages[0]['content']|trim %} {%- set "
90
+ ... 'messages = messages[1:] %} {%- else %} {{- raise_exception("Cannot put tools in the first user '
91
+ ... "message when there's no first user message!\\") }} {%- endif %} {{- "
92
+ ... "'<|start_header_id|>user<|end_header_id|>\\n\\n' -}} {{- \\"Given the following functions, please "
93
+ ... 'respond with a JSON for a function call " }} {{- "with its proper arguments that best answers the '
94
+ ... 'given prompt.\\n\\n" }} {{- \\'Respond in the format {"name": function name, "parameters": '
95
+ ... 'dictionary of argument name and its value}.\\' }} {{- "Do not use variables.\\n\\n" }} {%- for t in '
96
+ ... 'tools %} {{- t | tojson(indent=4) }} {{- "\\n\\n" }} {%- endfor %} {{- first_user_message + '
97
+ ... "\\"<|eot_id|>\\"}} {%- endif %} {%- for message in messages %} {%- if not (message.role == 'ipython' "
98
+ ... "or message.role == 'tool' or 'tool_calls' in message) %} {{- '<|start_header_id|>' + message['role']"
99
+ ... " + '<|end_header_id|>\\n\\n'+ message['content'] | trim + '<|eot_id|>' }} {%- elif 'tool_calls' in "
100
+ ... 'message %} {%- if not message.tool_calls|length == 1 %} {{- raise_exception("This model only '
101
+ ... 'supports single tool-calls at once!") }} {%- endif %} {%- set tool_call = message.tool_calls[0]'
102
+ ... ".function %} {%- if builtin_tools is defined and tool_call.name in builtin_tools %} {{- "
103
+ ... "'<|start_header_id|>assistant<|end_header_id|>\\n\\n' -}} {{- \\"<|python_tag|>\\" + tool_call.name + "
104
+ ... '".call(" }} {%- for arg_name, arg_val in tool_call.arguments | items %} {{- arg_name + \\'="\\' + '
105
+ ... 'arg_val + \\'"\\' }} {%- if not loop.last %} {{- ", " }} {%- endif %} {%- endfor %} {{- ")" }} {%- '
106
+ ... "else %} {{- '<|start_header_id|>assistant<|end_header_id|>\\n\\n' -}} {{- '{\\"name\": \\"' + "
107
+ ... 'tool_call.name + \\'", \\' }} {{- \\'"parameters": \\' }} {{- tool_call.arguments | tojson }} {{- "}" '
108
+ ... "}} {%- endif %} {%- if builtin_tools is defined %} {#- This means we're in ipython mode #} {{- "
109
+ ... '"<|eom_id|>" }} {%- else %} {{- "<|eot_id|>" }} {%- endif %} {%- elif message.role == "tool" '
110
+ ... 'or message.role == "ipython" %} {{- "<|start_header_id|>ipython<|end_header_id|>\\n\\n" }} {%- '
111
+ ... "if message.content is mapping or message.content is iterable %} {{- message.content | tojson }} {%- "
112
+ ... 'else %} {{- message.content }} {%- endif %} {{- "<|eot_id|>" }} {%- endif %} {%- endfor %} {%- if '
113
+ ... "add_generation_prompt %} {{- '<|start_header_id|>assistant<|end_header_id|>\\n\\n' }} {%- endif %} "
114
+ ... )
115
+ >>> prompt_assembler = (
116
+ ... PromptAssembler()
117
+ ... .setInputCol("messages")
118
+ ... .setOutputCol("prompt")
119
+ ... .setChatTemplate(template)
120
+ ... )
121
+ >>> prompt_assembler.transform(df).select("prompt.result").show(truncate=False)
122
+ +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
123
+ |result |
124
+ +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
125
+ |[<|start_header_id|>system<|end_header_id|>\\n\\nYou are a helpful assistant.<|eot_id|><|start_header_id|>assistant<|end_header_id|>\\n\\nHello there, how can I help you?<|eot_id|><|start_header_id|>user<|end_header_id|>\\n\\nI need help with organizing my room.<|eot_id|><|start_header_id|>assistant<|end_header_id|>\\n\\n]|
126
+ +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
127
+ """
128
+
129
+ outputAnnotatorType = AnnotatorType.DOCUMENT
130
+
131
+ inputCol = Param(
132
+ Params._dummy(),
133
+ "inputCol",
134
+ "input column name",
135
+ typeConverter=TypeConverters.toString,
136
+ )
137
+ outputCol = Param(
138
+ Params._dummy(),
139
+ "outputCol",
140
+ "output column name",
141
+ typeConverter=TypeConverters.toString,
142
+ )
143
+ chatTemplate = Param(
144
+ Params._dummy(),
145
+ "chatTemplate",
146
+ "Template used for the chat",
147
+ typeConverter=TypeConverters.toString,
148
+ )
149
+ addAssistant = Param(
150
+ Params._dummy(),
151
+ "addAssistant",
152
+ "Whether to add an assistant header to the end of the generated string",
153
+ typeConverter=TypeConverters.toBoolean,
154
+ )
155
+ name = "PromptAssembler"
156
+
157
+ @keyword_only
158
+ def __init__(self):
159
+ super(PromptAssembler, self).__init__(
160
+ classname="com.johnsnowlabs.nlp.PromptAssembler"
161
+ )
162
+ self._setDefault(outputCol="prompt", addAssistant=True)
163
+
164
+ @keyword_only
165
+ def setParams(self):
166
+ kwargs = self._input_kwargs
167
+ return self._set(**kwargs)
168
+
169
+ def setInputCol(self, value):
170
+ """Sets input column name.
171
+
172
+ Parameters
173
+ ----------
174
+ value : str
175
+ Name of the input column
176
+ """
177
+ return self._set(inputCol=value)
178
+
179
+ def setOutputCol(self, value):
180
+ """Sets output column name.
181
+
182
+ Parameters
183
+ ----------
184
+ value : str
185
+ Name of the Output Column
186
+ """
187
+ return self._set(outputCol=value)
188
+
189
+ def setChatTemplate(self, value):
190
+ """Sets the chat template.
191
+
192
+ Parameters
193
+ ----------
194
+ value : str
195
+ Template used for the chat
196
+ """
197
+ return self._set(chatTemplate=value)
198
+
199
+ def setAddAssistant(self, value):
200
+ """Sets whether to add an assistant header to the end of the generated string.
201
+
202
+ Parameters
203
+ ----------
204
+ value : bool
205
+ Whether to add an assistant header to the end of the generated string
206
+ """
207
+ return self._set(addAssistant=value)
@@ -29,7 +29,7 @@ class TokenAssembler(AnnotatorTransformer, AnnotatorProperties):
29
29
  annotators. Requires ``DOCUMENT`` and ``TOKEN`` type annotations as input.
30
30
 
31
31
  For more extended examples on document pre-processing see the
32
- `Spark NLP Workshop <https://github.com/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/Certification_Trainings/Public/2.Text_Preprocessing_with_SparkNLP_Annotators_Transformers.ipynb>`__.
32
+ `Examples <https://github.com/JohnSnowLabs/spark-nlp/blob/master/examples/python/annotation/text/english/token-assembler/Assembling_Tokens_to_Documents.ipynb>`__.
33
33
 
34
34
  ====================== ======================
35
35
  Input Annotation types Output Annotation type
@@ -122,4 +122,3 @@ class TokenAssembler(AnnotatorTransformer, AnnotatorProperties):
122
122
  Name of the Id Column
123
123
  """
124
124
  return self._set(preservePosition=value)
125
-
@@ -22,3 +22,5 @@ from sparknlp.common.recursive_annotator_approach import *
22
22
  from sparknlp.common.storage import *
23
23
  from sparknlp.common.utils import *
24
24
  from sparknlp.common.annotator_type import *
25
+ from sparknlp.common.match_strategy import *
26
+ from sparknlp.common.completion_post_processing import *
@@ -35,3 +35,4 @@ class AnnotatorType(object):
35
35
  NODE = "node"
36
36
  TABLE = "table"
37
37
  DUMMY = "dummy"
38
+ DOC_SIMILARITY_RANKINGS = "doc_similarity_rankings"
@@ -0,0 +1,37 @@
1
+ # Copyright 2017-2025 John Snow Labs
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from pyspark.ml.param import Param, Params, TypeConverters
15
+
16
+
17
+ class CompletionPostProcessing:
18
+ removeThinkingTag = Param(
19
+ Params._dummy(),
20
+ "removeThinkingTag",
21
+ "Set a thinking tag (e.g. think) to be removed from output. Will match <TAG>...</TAG>",
22
+ typeConverter=TypeConverters.toString,
23
+ )
24
+
25
+ def setRemoveThinkingTag(self, value: str):
26
+ """Set a thinking tag (e.g. `think`) to be removed from output.
27
+ Will produce the regex: `(?s)<$TAG>.+?</$TAG>`
28
+ """
29
+ self._set(removeThinkingTag=value)
30
+ return self
31
+
32
+ def getRemoveThinkingTag(self):
33
+ """Get the thinking tag to be removed from output."""
34
+ value = None
35
+ if self.removeThinkingTag in self._paramMap:
36
+ value = self._paramMap[self.removeThinkingTag]
37
+ return value
@@ -0,0 +1,33 @@
1
+ # Copyright 2017-2023 John Snow Labs
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Allowed strategies for RuleFactory applications regarding replacement"""
16
+
17
+
18
+ class MatchStrategy(object):
19
+ """Object that contains constants for how for matched strategies used in RuleFactory.
20
+
21
+ Possible values are:
22
+
23
+ ================================== ===============================================================================
24
+ Value Description
25
+ ================================== ===============================================================================
26
+ ``MatchStrategy.MATCH_ALL`` This strategy matches all occurrences of all rules in the given text.
27
+ ``MatchStrategy.MATCH_FIRST`` This strategy matches only the first occurrence of each rule in the given text.
28
+ ``MatchStrategy.MATCH_COMPLETE`` This strategy matches only the first occurrence of each rule in the given text.
29
+ ================================== ===============================================================================
30
+ """
31
+ MATCH_ALL = "MATCH_ALL"
32
+ MATCH_FIRST = "MATCH_FIRST"
33
+ MATCH_COMPLETE = "MATCH_COMPLETE"