|
| 1 | +# SPDX-FileCopyrightText: 2026 PyThaiNLP Project |
| 2 | +# SPDX-FileType: SOURCE |
| 3 | +# SPDX-License-Identifier: Apache-2.0 |
| 4 | +""" |
| 5 | +Example: Using PyThaiNLP in PySpark Distributed Environment |
| 6 | +
|
| 7 | +This example demonstrates how to use PyThaiNLP in a distributed environment |
| 8 | +like Apache Spark. The key is to set the PYTHAINLP_DATA_DIR environment |
| 9 | +variable inside the function that will be distributed to executor nodes. |
| 10 | +
|
| 11 | +PyThaiNLP's core tokenization engines are thread-safe, making them suitable |
| 12 | +for distributed computing environments where multiple threads may process |
| 13 | +data concurrently. For detailed information about thread safety, see: |
| 14 | +https://github.com/PyThaiNLP/pythainlp/blob/dev/docs/threadsafe.rst |
| 15 | +
|
| 16 | +For information about data directory configuration in distributed environments, see: |
| 17 | +https://github.com/PyThaiNLP/pythainlp/issues/475 |
| 18 | +""" |
| 19 | + |
| 20 | + |
| 21 | +# Example 1: Basic PySpark setup with PyThaiNLP |
| 22 | +def example_basic_spark(): |
| 23 | + """ |
| 24 | + Basic example showing how to tokenize Thai text in PySpark. |
| 25 | + """ |
| 26 | + from pyspark import SparkContext |
| 27 | + |
| 28 | + sc = SparkContext("local[*]", "PyThaiNLP Example") |
| 29 | + |
| 30 | + # Sample Thai text data |
| 31 | + thai_texts = [ |
| 32 | + "สวัสดีครับ ผมชื่อจอห์น", |
| 33 | + "ภาษาไทยเป็นภาษาที่สวยงาม", |
| 34 | + "PyThaiNLP ช่วยประมวลผลภาษาไทย", |
| 35 | + ] |
| 36 | + |
| 37 | + rdd = sc.parallelize(thai_texts) |
| 38 | + |
| 39 | + def tokenize_thai(text): |
| 40 | + """ |
| 41 | + Tokenize Thai text using PyThaiNLP. |
| 42 | +
|
| 43 | + IMPORTANT: Import and configure environment variables INSIDE the function |
| 44 | + that will be distributed to executor nodes. |
| 45 | + """ |
| 46 | + import os |
| 47 | + |
| 48 | + # Set PYTHAINLP_DATA_DIR before importing pythainlp |
| 49 | + # Use './pythainlp-data' to store data in current working directory |
| 50 | + os.environ["PYTHAINLP_DATA_DIR"] = "./pythainlp-data" |
| 51 | + |
| 52 | + # Now import pythainlp modules |
| 53 | + from pythainlp.tokenize import word_tokenize |
| 54 | + |
| 55 | + # Perform tokenization |
| 56 | + return word_tokenize(text) |
| 57 | + |
| 58 | + # Apply tokenization to all texts in parallel |
| 59 | + tokenized_rdd = rdd.map(tokenize_thai) |
| 60 | + |
| 61 | + # Collect results |
| 62 | + results = tokenized_rdd.collect() |
| 63 | + for text, tokens in zip(thai_texts, results): |
| 64 | + print(f"Text: {text}") |
| 65 | + print(f"Tokens: {tokens}\n") |
| 66 | + |
| 67 | + sc.stop() |
| 68 | + |
| 69 | + |
| 70 | +# Example 2: Using DataFrame API |
| 71 | +def example_dataframe_api(): |
| 72 | + """ |
| 73 | + Example using PySpark DataFrame API with PyThaiNLP. |
| 74 | + """ |
| 75 | + from pyspark.sql import SparkSession |
| 76 | + from pyspark.sql.functions import udf |
| 77 | + from pyspark.sql.types import ArrayType, StringType |
| 78 | + |
| 79 | + spark = SparkSession.builder.appName("PyThaiNLP DataFrame Example").getOrCreate() |
| 80 | + |
| 81 | + # Create sample DataFrame |
| 82 | + data = [ |
| 83 | + (1, "สวัสดีครับ ผมชื่อจอห์น"), |
| 84 | + (2, "ภาษาไทยเป็นภาษาที่สวยงาม"), |
| 85 | + (3, "PyThaiNLP ช่วยประมวลผลภาษาไทย"), |
| 86 | + ] |
| 87 | + df = spark.createDataFrame(data, ["id", "text"]) |
| 88 | + |
| 89 | + # Define UDF for tokenization |
| 90 | + @udf(returnType=ArrayType(StringType())) |
| 91 | + def tokenize_udf(text): |
| 92 | + """ |
| 93 | + UDF for tokenizing Thai text. |
| 94 | +
|
| 95 | + IMPORTANT: Set environment variable and import inside the UDF. |
| 96 | + """ |
| 97 | + import os |
| 98 | + |
| 99 | + os.environ["PYTHAINLP_DATA_DIR"] = "./pythainlp-data" |
| 100 | + |
| 101 | + from pythainlp.tokenize import word_tokenize |
| 102 | + |
| 103 | + return word_tokenize(text) |
| 104 | + |
| 105 | + # Apply tokenization |
| 106 | + result_df = df.withColumn("tokens", tokenize_udf(df.text)) |
| 107 | + |
| 108 | + # Show results |
| 109 | + result_df.show(truncate=False) |
| 110 | + |
| 111 | + spark.stop() |
| 112 | + |
| 113 | + |
| 114 | +# Example 3: Advanced configuration with multiple PyThaiNLP features |
| 115 | +def example_advanced(): |
| 116 | + """ |
| 117 | + Advanced example using multiple PyThaiNLP features in PySpark. |
| 118 | + """ |
| 119 | + from pyspark import SparkContext |
| 120 | + |
| 121 | + sc = SparkContext("local[*]", "PyThaiNLP Advanced Example") |
| 122 | + |
| 123 | + thai_texts = [ |
| 124 | + "สวัสดีครับ ผมชื่อจอห์น", |
| 125 | + "ภาษาไทยเป็นภาษาที่สวยงาม", |
| 126 | + ] |
| 127 | + |
| 128 | + rdd = sc.parallelize(thai_texts) |
| 129 | + |
| 130 | + def process_thai_text(text): |
| 131 | + """ |
| 132 | + Process Thai text with multiple PyThaiNLP features. |
| 133 | + """ |
| 134 | + import os |
| 135 | + |
| 136 | + # Configure data directory |
| 137 | + os.environ["PYTHAINLP_DATA_DIR"] = "./pythainlp-data" |
| 138 | + |
| 139 | + # Import required modules |
| 140 | + from pythainlp.tag import pos_tag |
| 141 | + from pythainlp.tokenize import word_tokenize |
| 142 | + from pythainlp.util import normalize |
| 143 | + |
| 144 | + # Normalize text |
| 145 | + normalized = normalize(text) |
| 146 | + |
| 147 | + # Tokenize |
| 148 | + tokens = word_tokenize(normalized) |
| 149 | + |
| 150 | + # POS tagging |
| 151 | + tagged = pos_tag(tokens) |
| 152 | + |
| 153 | + return { |
| 154 | + "original": text, |
| 155 | + "normalized": normalized, |
| 156 | + "tokens": tokens, |
| 157 | + "pos_tags": tagged, |
| 158 | + } |
| 159 | + |
| 160 | + # Process all texts |
| 161 | + results = rdd.map(process_thai_text).collect() |
| 162 | + |
| 163 | + for result in results: |
| 164 | + print(f"Original: {result['original']}") |
| 165 | + print(f"Normalized: {result['normalized']}") |
| 166 | + print(f"Tokens: {result['tokens']}") |
| 167 | + print(f"POS Tags: {result['pos_tags']}\n") |
| 168 | + |
| 169 | + sc.stop() |
| 170 | + |
| 171 | + |
| 172 | +# Example 4: Best practices for production environments |
| 173 | +def example_production_best_practices(): |
| 174 | + """ |
| 175 | + Production-ready example with error handling and logging. |
| 176 | + """ |
| 177 | + from pyspark.sql import SparkSession |
| 178 | + |
| 179 | + spark = ( |
| 180 | + SparkSession.builder.appName("PyThaiNLP Production Example") |
| 181 | + .config("spark.python.worker.reuse", "true") # Reuse Python workers |
| 182 | + .getOrCreate() |
| 183 | + ) |
| 184 | + |
| 185 | + data = [ |
| 186 | + (1, "สวัสดีครับ ผมชื่อจอห์น"), |
| 187 | + (2, "ภาษาไทยเป็นภาษาที่สวยงาม"), |
| 188 | + (3, None), # Test handling of None |
| 189 | + ] |
| 190 | + df = spark.createDataFrame(data, ["id", "text"]) |
| 191 | + |
| 192 | + def safe_tokenize(text): |
| 193 | + """ |
| 194 | + Tokenize with error handling for production use. |
| 195 | + """ |
| 196 | + import os |
| 197 | + |
| 198 | + try: |
| 199 | + # Set environment variables |
| 200 | + os.environ["PYTHAINLP_DATA_DIR"] = "./pythainlp-data" |
| 201 | + |
| 202 | + # Import modules |
| 203 | + from pythainlp.tokenize import word_tokenize |
| 204 | + |
| 205 | + # Handle None or empty strings |
| 206 | + if not text: |
| 207 | + return [] |
| 208 | + |
| 209 | + return word_tokenize(text) |
| 210 | + |
| 211 | + except Exception as e: |
| 212 | + # Log error (in production, use proper logging) |
| 213 | + print(f"Error tokenizing text: {text}, Error: {str(e)}") |
| 214 | + return [] |
| 215 | + |
| 216 | + # Register UDF |
| 217 | + from pyspark.sql.functions import udf |
| 218 | + from pyspark.sql.types import ArrayType, StringType |
| 219 | + |
| 220 | + tokenize_udf = udf(safe_tokenize, ArrayType(StringType())) |
| 221 | + |
| 222 | + # Apply tokenization |
| 223 | + result_df = df.withColumn("tokens", tokenize_udf(df.text)) |
| 224 | + result_df.show(truncate=False) |
| 225 | + |
| 226 | + spark.stop() |
| 227 | + |
| 228 | + |
| 229 | +if __name__ == "__main__": |
| 230 | + print("=" * 70) |
| 231 | + print("PyThaiNLP in PySpark - Examples") |
| 232 | + print("=" * 70) |
| 233 | + print("\nNote: These examples require Apache Spark to be installed:") |
| 234 | + print(" pip install pyspark") |
| 235 | + print("\nChoose an example to run:") |
| 236 | + print("1. Basic Spark example") |
| 237 | + print("2. DataFrame API example") |
| 238 | + print("3. Advanced features example") |
| 239 | + print("4. Production best practices example") |
| 240 | + print("\nTo run a specific example, uncomment the corresponding line below:") |
| 241 | + print("=" * 70) |
| 242 | + |
| 243 | + # Uncomment one of these to run: |
| 244 | + # example_basic_spark() |
| 245 | + # example_dataframe_api() |
| 246 | + # example_advanced() |
| 247 | + # example_production_best_practices() |
| 248 | + |
| 249 | + print("\n✓ Examples loaded successfully!") |
| 250 | + print("Uncomment an example function call to run it.") |
0 commit comments