### Database Setup and Session Management
Source: https://context7.com/giacomo-de-luca/process-sanskrit/llms.txt
Utilities for database initialization and session management for optimal performance.
```APIDOC
## Database Setup and Session Management
### Description
Utilities for database initialization and session management for optimal performance.
### Database Initialization
Run from command line:
```bash
update-ps-database
```
Or programmatically:
```python
from process_sanskrit.setup.updateDB import update_database
update_database()
```
### Database Session Management
Get a database session for batch operations.
```python
from process_sanskrit.utils.databaseSetup import get_session
session = get_session()
# Use session with all functions for better performance
import process_sanskrit as ps
words = ['yoga', 'dharma', 'karma', 'nirvāṇa', 'saṃsāra']
for word in words:
result = ps.process(word, 'mw', 'ap90', session=session)
# Process result...
# Always close session when done
session.close()
```
#### Context Manager Pattern (Recommended)
```python
from contextlib import contextmanager
from process_sanskrit.utils.databaseSetup import get_session
@contextmanager
def sanskrit_session():
session = get_session()
try:
yield session
finally:
session.close()
# Usage
with sanskrit_session() as session:
for word in word_list:
result = ps.process(word, session=session)
```
### Get Database Engine
Get the database engine for advanced operations.
```python
from process_sanskrit.utils.databaseSetup import get_engine
engine = get_engine()
# Use for direct SQL queries or custom operations
```
### Check Database Status
Check if the database is initialized.
```python
import os
from process_sanskrit.utils.databaseSetup import DB_PATH
if os.path.exists(DB_PATH):
print("Database initialized")
else:
print("Run update-ps-database first")
```
```
--------------------------------
### Database Setup and Session Management in Python
Source: https://context7.com/giacomo-de-luca/process-sanskrit/llms.txt
Python code demonstrating database initialization and session management for the process_sanskrit library. It shows how to update the database, obtain a session for batch operations, and use a context manager for recommended session handling.
```python
from process_sanskrit.utils.databaseSetup import get_session, get_engine
from process_sanskrit.setup.updateDB import update_database
import process_sanskrit as ps
from contextlib import contextmanager
import os
from process_sanskrit.utils.databaseSetup import DB_PATH
# Initialize database (first-time setup)
# update_database()
# Get database session for batch operations
session = get_session()
words = ['yoga', 'dharma', 'karma', 'nirvāṇa', 'saṃsāra']
for word in words:
result = ps.process(word, 'mw', 'ap90', session=session)
# Process result...
# Always close session when done
session.close()
# Context manager pattern (recommended)
@contextmanager
def sanskrit_session():
session = get_session()
try:
yield session
finally:
session.close()
# Usage with context manager
# with sanskrit_session() as session:
# for word in word_list:
# result = ps.process(word, session=session)
# Get engine for advanced operations
engine = get_engine()
# Check database status
if os.path.exists(DB_PATH):
print("Database initialized")
else:
print("Run update-ps-database first")
```
--------------------------------
### Experimental BYT5 Text Preprocessing and Processing
Source: https://github.com/giacomo-de-luca/process-sanskrit/blob/main/README.md
An experimental function that preprocesses text using the BYT5 model and then applies stemming and grammatical analysis using the standard process function. Requires installation with BYT5 support and database update. Dependencies: process-sanskrit[byt5], update-ps-database.
```python
!pip install process-sanskrit[byt5]
!update-ps-database
from process_sanskrit.functions import processBYT5
ps.process(‘śrutam amavijñānaṃ tat sāmānyaviṣayam’)
```
--------------------------------
### Flask API Wrapper for Process-Sanskrit
Source: https://context7.com/giacomo-de-luca/process-sanskrit/llms.txt
Demonstrates the integration of Process-Sanskrit functionality into a web application using a Flask API wrapper. Includes examples of how to use `curl` to interact with the API for text processing, dictionary lookups, and transliteration.
```python
from process_sanskrit.utils.processAPI import app
import process_sanskrit as ps
from flask import Flask, request, jsonify
# Start the API server
# python -m process_sanskrit.utils.processAPI
# POST /process - Process Sanskrit text
# Request body: raw text string
# Response: JSON array of processed results
"""
curl -X POST http://localhost:5000/process \
-H "Content-Type: text/plain" \
-d "yogaścittavṛttinirodhaḥ"
"""
# POST /dict_entry - Dictionary lookup
# Request JSON: {"word": "yoga", "dictionaries": ["mw", "ap90"]}
# Response: JSON array of dictionary entries
"""
curl -X POST http://localhost:5000/dict_entry \
-H "Content-Type: application/json" \
-d '{"word": "yoga", "dictionaries": ["mw", "ap90"]}'
"""
# POST /transliterate - Transliteration
```
--------------------------------
### Process BYT5 - Experimental Neural Model Text Processing
Source: https://context7.com/giacomo-de-luca/process-sanskrit/llms.txt
Introduces the experimental processBYT5 function, which leverages the BYT5 neural model for advanced text segmentation and morphological analysis. This function is intended for use before standard pipeline processing and requires specific installation with BYT5 dependencies.
```python
from process_sanskrit.functions.processBYT5 import processBYT5
# Note: Requires installation with BYT5 dependencies
```
--------------------------------
### Transliterate Sanskrit Text using Curl
Source: https://context7.com/giacomo-de-luca/process-sanskrit/llms.txt
Example of how to transliterate Sanskrit text using the provided API endpoint with curl. It demonstrates sending a JSON payload with the text and desired transliteration scheme.
```bash
curl -X POST http://localhost:5000/transliterate \
-H "Content-Type: application/json" \
-d '{"text": "योग", "transliteration_scheme": "IAST"}'
```
--------------------------------
### Run BYT5 Model Inference for Sanskrit NLP
Source: https://context7.com/giacomo-de-luca/process-sanskrit/llms.txt
Provides examples of using the low-level `run_inference` function for various Sanskrit NLP tasks powered by the BYT5 model. Supports segmentation, morphosyntactic tagging, lemmatization, and full pipeline analysis. It also demonstrates batch processing with custom batch sizes.
```python
from process_sanskrit.functions.model_inference import run_inference
# Segmentation only
sentences = [
'athayogānuśāsanam',
'yogaścittavṛttinirodhaḥ'
]
segmented = run_inference(sentences, mode="segmentation")
# Segmentation with morphosyntactic tags
result = run_inference(
['cittavṛttinirodhaḥ'],
mode="segmentation-morphosyntax"
)
# Lemmatization
lemmas = run_inference(
['yogena', 'dharmeṇa', 'karmaṇā'],
mode="lemma"
)
# Lemmatization with morphosyntax
result = run_inference(
['yogena'],
mode="lemma-morphosyntax"
)
# Full pipeline - segmentation + lemma + morphosyntax
result = run_inference(
['tadā draṣṭuḥ svarūpe avasthānam'],
mode="segmentation-lemma-morphosyntax"
)
# Batch processing with custom batch size
large_corpus = ['text1', 'text2', ...] # 100 texts
results = run_inference(
large_corpus,
mode="segmentation",
batch_size=50 # Process 50 at a time
)
```
--------------------------------
### Process Sanskrit text with pipeline analysis
Source: https://context7.com/giacomo-de-luca/process-sanskrit/llms.txt
Main function for processing Sanskrit text through a complete pipeline including sandhi splitting, compound resolution, and dictionary lookup. Supports multiple transliteration formats and processing modes. Requires process_sanskrit library installation.
```python
import process_sanskrit as ps
# Basic usage - single word analysis with default Monier-Williams dictionary
result = ps.process("pratiprasave")
# Returns: [
# 'pratiprasava', # word stem
# 'masculine noun/adjective ending in a', # grammatical type
# [('Loc', 'Sg')], # case/inflection
# ['pratiprasavaḥ', 'pratiprasavau', 'pratiprasavāḥ', ...], # inflection table
# 'pratiprasave', # original word
# 'prati—prasava', # word components
# {'mw': {'pratiprasava': ['prati—prasava...']}} # dictionary entries
# ]
# Multiple dictionary lookup
result = ps.process('saṃskāra', 'ap90', 'cae', 'gra', 'bhs')
# Searches in Apte, Cappeller, Grassmann, and Edgerton Buddhist dictionaries
# Roots mode - extract only root forms from complex compounds
roots = ps.process('yamaniyamāsanaprāṇāyāmapratyāhāradhāraṇādhyānasamādhayo',
mode='roots')
# Returns: ['yama', 'niyama', 'asana', 'prāṇāyāma', 'pratyāhāra',
# 'dhāraṇa', 'dhyāna', 'samādhi']
# Complex philosophical compound analysis
result = ps.process("cittavṛttinirodhaḥ", mode='detailed')
# Splits compound, finds roots, provides grammatical info and dictionary entries
# Wildcard dictionary search
ps.process("deva*") # Finds all words starting with 'deva'
ps.process("dev_") # Finds 4-letter words starting with 'dev'
# Pre-split compounds with hyphens
ps.process("deva-datta") # Processes hyphen-separated components
# Parts mode - get compound components mapping
parts = ps.process("dharmārthakāmamokṣāḥ", mode='parts')
# Returns: {'dharmārthakāmamokṣāḥ': ['dharma', 'artha', 'kāma', 'mokṣa']}
# Auto-detection of transliteration scheme
ps.process("pataJjali") # HK format - auto-converted to IAST
ps.process("patañjali") # IAST format - used directly
ps.process("पतञ्जलि") # Devanagari - auto-converted to IAST
# Performance optimization with database session
from process_sanskrit.utils.databaseSetup import get_session
session = get_session()
for word in ['yoga', 'dharma', 'karma']:
result = ps.process(word, 'mw', 'ap90', session=session)
session.close()
```
--------------------------------
### Process Sanskrit Text with BYT5 Model
Source: https://context7.com/giacomo-de-luca/process-sanskrit/llms.txt
Demonstrates basic and advanced usage of the processBYT5 function for Sanskrit text processing. This includes getting root forms, detailed analysis with multiple dictionaries, and batch processing of multiple texts. The function leverages the BYT5 model for neural segmentation and processing.
```python
import process_sanskrit
# Basic usage - neural segmentation + processing
result = process_sanskrit.processBYT5('śrutam āgamavijñānaṃ tat sāmānyaviṣayam')
# Get only root forms
roots = process_sanskrit.processBYT5(
'yamaniyamāsanaprāṇāyāmapratyāhāra',
mode='roots'
)
# Detailed analysis
result = process_sanskrit.processBYT5(
'cittavṛttinirodhaḥ',
mode='detailed',
'mw', 'ap90'
)
# Batch processing
texts = [
'atha yogānuśāsanam',
'yogaścittavṛttinirodhaḥ',
'tadā draṣṭuḥ svarūpe avasthānam'
]
results = process_sanskrit.processBYT5(texts, mode='roots')
# Parts mode - get compound components
parts = process_sanskrit.processBYT5(
'dharmārthakāmamokṣāḥ',
mode='parts'
)
```
--------------------------------
### Hybrid Sandhi Splitter - Detailed Output and Scoring
Source: https://context7.com/giacomo-de-luca/process-sanskrit/llms.txt
Demonstrates how to use the hybrid_sandhi_splitter function to analyze Sanskrit text. It shows how to get detailed output including scoring information, adjust score thresholds for quality control, and control the number of attempts for the statistical parser. The function automatically selects the best approach (statistical or compound analysis) based on scoring and handles both vowel and consonant sandhi.
```python
from process_sanskrit.sandhi import hybrid_sandhi_splitter
# Detailed output with scoring information
split, score, subscores, all_splits = hybrid_sandhi_splitter(
"dharmārthakāmamokṣāḥ",
detailed_output=True
)
# Returns tuple: (best_split, overall_score, component_scores, all_attempts)
# Adjust score threshold for quality control
split = hybrid_sandhi_splitter(
"rāmalakṣmaṇau",
score_threshold=0.6 # Higher threshold = more conservative
)
# Returns: ['rāma', 'lakṣmaṇa']
# Control number of attempts for statistical parser
split = hybrid_sandhi_splitter(
"compound_text",
attempts=30 # More attempts = more exhaustive search
)
# Automatic algorithm selection
# Uses statistical parser first, falls back to compound analysis if score low
split = hybrid_sandhi_splitter("cittavṛttinirodhaḥ")
# Automatically chooses best approach based on scoring
# Handles vowel sandhi
split = hybrid_sandhi_splitter("rāmāyaṇa") # rāma + ayaṇa
split = hybrid_sandhi_splitter("mahendraḥ") # mahā + indraḥ
# Handles consonant sandhi
split = hybrid_sandhi_splitter("vāgīśa") # vāk + īśa
```
--------------------------------
### Inflect Function - Word List Processing for Roots
Source: https://context7.com/giacomo-de-luca/process-sanskrit/llms.txt
Shows how to use the inflect function to process lists of Sanskrit words, primarily for identifying root forms after sandhi splitting. It covers handling prefixes, combining words with prefixes to form new roots (e.g., sam + yoga = saṃyoga), and managing multiple prefixes. The function also includes fallback mechanisms for unresolved words by calling compound analysis internally and offers a debug mode for tracing the processing steps. Examples include common Sanskrit prefixes and real-world usage from texts.
```python
from process_sanskrit.functions.inflect import inflect
from process_sanskrit.utils.databaseSetup import get_session
session = get_session()
# Process list of split words
words = ['yogaḥ', 'citta', 'vṛtti', 'nirodhaḥ']
roots = inflect(words, session=session)
# Returns: ['yoga', 'citta', 'vṛtti', 'nirodha']
# Handles prefix detection and combination
words = ['sam', 'yoga']
roots = inflect(words, session=session)
# Returns: ['saṃyoga'] - combines prefix with following word
# Multiple prefixes
words = ['pra', 'vi', 'bhāga']
roots = inflect(words, session=session)
# Returns: ['pravibhāga']
# Common Sanskrit prefixes handled:
# sva, anu, sam, pra, upa, vi, ni, apa, adhi, abhi, ati, etc.
# Mixed content - some prefixes, some standalone words
words = ['pra', 'yoga', 'tat', 'dharma']
roots = inflect(words, session=session)
# Returns: ['prayoga', 'tad', 'dharma']
# Handles prefix variations
words = ['sam', 'kāra'] # sam + kāra → saṃskāra
roots = inflect(words, session=session)
# Returns: ['saṃskāra']
words = ['vi', 'āsa'] # vi + āsa → vyāsa
roots = inflect(words, session=session)
# Returns: ['vyāsa']
# Falls back to compound analysis for unresolved words
words = ['cittavṛtti'] # Not in inflection tables
roots = inflect(words, session=session)
# Calls root_compounds internally, returns: ['citta', 'vṛtti']
# Debug mode
roots = inflect(words, debug=True, session=session)
# Prints processing steps
# Real example from Yoga Sutra
words = ['tadā', 'draṣṭuḥ', 'svarūpe', 'avasthānam']
roots = inflect(words, session=session)
# Returns analyzed root forms for each word
session.close()
```
--------------------------------
### Compound Analysis - Dictionary-Based Word Segmentation
Source: https://context7.com/giacomo-de-luca/process-sanskrit/llms.txt
Utilizes the root_compounds function for dictionary-based segmentation of Sanskrit compounds. It demonstrates basic splitting, handling complex dvandva and tatpuruṣa compounds, and very long compounds from texts like the Yoga Sutras. The function supports options for including inflection information, enabling debug mode for development, and correctly handles sandhi at component boundaries, including vowel sandhi. Examples for bahuvrīhi and karmadhāraya compounds are also provided.
```python
from process_sanskrit.functions.compoundAnalysis import root_compounds
from process_sanskrit.utils.databaseSetup import get_session
session = get_session()
# Basic compound splitting
parts = root_compounds("dharmārthakāmamokṣāḥ", session=session)
# Returns: ['dharma', 'artha', 'kāma', 'mokṣa']
# Complex dvandva compound
parts = root_compounds("rāmalakṣmaṇasītāhanumān", session=session)
# Returns: ['rāma', 'lakṣmaṇa', 'sītā', 'hanumān']
# Tatpuruṣa compound
parts = root_compounds("rājapuruṣaḥ", session=session)
# Returns: ['rāja', 'puruṣa']
# Very long compound from Yoga Sutras
parts = root_compounds(
"yamaniyamāsanaprāṇāyāmapratyāhāradhāraṇādhyānasamādhayaḥ",
session=session
)
# Returns: ['yama', 'niyama', 'āsana', 'prāṇāyāma', 'pratyāhāra',
# 'dhāraṇa', 'dhyāna', 'samādhi']
# With inflection information
parts = root_compounds("cittavṛttinirodhaḥ", inflection=True, session=session)
# Returns detailed inflection analysis for each component
# Debug mode for development
parts = root_compounds("compound_word", debug=True, session=session)
# Prints step-by-step matching process
# Handles sandhi at boundaries
parts = root_compounds("vāgīśa", session=session) # vāk + īśa
parts = root_compounds("mahendraḥ", session=session) # mahā + indraḥ
# Handles vowel sandhi between components
parts = root_compounds("rāmāyaṇa", session=session) # rāma + ayaṇa
# Bahuvrīhi compound
parts = root_compounds("mahābāhu", session=session)
# Returns: ['mahā', 'bāhu']
# Karmadhāraya compound
parts = root_compounds("nīlotpala", session=session) # nīla + utpala
# Returns: ['nīla', 'utpala']
session.close()
```
--------------------------------
### Process Sanskrit Text with Multiple Dictionaries
Source: https://github.com/giacomo-de-luca/process-sanskrit/blob/main/README.md
The 'process' function can search for words across multiple specified Sanskrit dictionaries. By default, it uses the Monnier Williams dictionary. To include additional dictionaries, provide their abbreviations as optional arguments. This example demonstrates retrieving entries for 'saṃskāra' from the Apte, Cappeller, Grassmann, and Edgerton dictionaries.
```python
import process_sanskrit as ps
print(ps.process('dvandva'))
print(ps.process('saṃskāra', 'ap90', 'cae', 'gra', 'bhs'))
```
--------------------------------
### Available Dictionaries
Source: https://github.com/giacomo-de-luca/process-sanskrit/blob/main/README.md
Information about the Sanskrit dictionaries supported by the library and their abbreviations.
```APIDOC
## Available Dictionaries
### Description
Lists the Sanskrit dictionaries available for use with the `process` function and their corresponding abbreviations.
### Dictionaries
- **'mw'**: Monier-Williams Sanskrit-English Dictionary
- **'ap90'**: Apte Practical Sanskrit-English Dictionary
- **'cae'**: Cappeller Sanskrit-English Dictionary
- **'ddsa'**: Macdonell A Practical Sanskrit Dictionary
- **'gra'**: Grassmann Wörterbuch zum Rig Veda
- **'bhs'**: Edgerton Buddhist Hybrid Sanskrit Dictionary
- **'cped'**: Concise Pali English Dictionary (for late Buddhist authors)
### Data Source
Most dictionaries are modified versions of the Cologne Digital Sanskrit Dictionaries (version 2.7.286, accessed February 19, 2025, https://www.sanskrit-lexicon.uni-koeln.de). The Concise Pali English Dictionary is by Buddhadatta Mahathera.
```
--------------------------------
### Stemming Mode
Source: https://github.com/giacomo-de-luca/process-sanskrit/blob/main/README.md
Utilize the 'process' function in 'roots' mode for efficient sandhi/compound splitting and stemming.
```APIDOC
## POST /process (mode='roots')
### Description
Processes Sanskrit text specifically for sandhi/compound splitting and stemming, returning only the root words.
### Method
POST
### Endpoint
/process
### Parameters
#### Request Body
- **text** (string) - Required - The Sanskrit text to process.
- **mode** (string) - Required - Set to 'roots' for stemming.
### Request Example
```json
{
"text": "yamaniyamāsanaprāṇāyāmapratyāhāradhāraṇādhyānasamādhayo",
"mode": "roots"
}
```
### Response
#### Success Response (200)
- **roots** (array of strings) - A list of stemmed words (roots).
#### Response Example
```json
{
"roots": [
"yama",
"niyama",
"asana",
"prāṇāyāma",
"pratyāhāra",
"dhāraṇa",
"dhyāna",
"samādhi"
]
}
```
```
--------------------------------
### Clean Results - Output Formatting Functions
Source: https://context7.com/giacomo-de-luca/process-sanskrit/llms.txt
Functions to format and clean processing results, including extracting roots, handling compound components, and managing duplicates.
```APIDOC
## Clean Results - Output Formatting Functions
### Description
Formats and cleans processing results, handling prefix combinations, duplicates, and extracting specific output formats.
### Method
POST (Implied, as it's a function call within a library)
### Endpoint
`clean_results`, `extract_roots`, `roots_splitted` (Internal functions)
### Parameters
- **raw_results** (list of lists) - Required - The raw output from the processing functions.
- **mode** (string) - Optional - The cleaning mode. Available modes: 'detailed', 'roots', 'parts'. Defaults to 'detailed'.
- **debug** (boolean) - Optional - If True, prints cleaning process steps.
### Request Example
```python
raw_results = [
['yoga', 'noun', [('Nom', 'Sg')], [...], 'yogaḥ', 'yoga', {...}],
['citta', 'noun', [('Nom', 'Sg')], [...], 'cittam', 'citta', {...}]
]
cleaned_detailed = clean_results(raw_results, mode='detailed')
roots_list = clean_results(raw_results, mode='roots')
compound_map = clean_results(raw_results, mode='parts')
roots_direct = extract_roots(raw_results)
special_prefix_cleaned = clean_results([['duḥ', ...], ['kha', ...]], mode='roots')
cleaned_debug = clean_results(raw_results, mode='detailed', debug=True)
```
### Response
#### Success Response (200)
- **cleaned_output** (list or dict) - The cleaned and formatted results, such as deduplicated entries, a list of roots, or a mapping of compounds to their components.
#### Response Example
```json
{
"cleaned_roots": [
"yoga",
"citta"
]
}
```
```
--------------------------------
### Clean and Format Sanskrit Processing Results
Source: https://context7.com/giacomo-de-luca/process-sanskrit/llms.txt
Illustrates how to use functions like `clean_results`, `extract_roots`, and `roots_splitted` to format and clean the output from Sanskrit processing. This includes deduplication, extracting specific formats like roots or compound components, and handling special prefix combinations.
```python
from process_sanskrit.functions.cleanResults import (
clean_results, extract_roots, roots_splitted
)
# Clean detailed results
raw_results = [
['yoga', 'noun', [('Nom', 'Sg')], [...], 'yogaḥ', 'yoga', {...}],
['citta', 'noun', [('Nom', 'Sg')], [...], 'cittam', 'citta', {...}]
]
cleaned = clean_results(raw_results, mode='detailed')
# Extract only roots
roots = clean_results(raw_results, mode='roots')
# Get compound component mapping
parts = clean_results(raw_results, mode='parts')
# Direct root extraction
roots_list = extract_roots(raw_results)
# Direct compound splitting extraction
compound_map = roots_splitted(raw_results)
# Handles special prefix combinations (duḥ + kha → duḥkha)
raw_with_prefix = [
['duḥ', ...],
['kha', ...]
]
cleaned = clean_results(raw_with_prefix, mode='roots')
# Debug mode
cleaned = clean_results(raw_results, mode='detailed', debug=True)
```
--------------------------------
### Search Sanskrit dictionaries with wildcards
Source: https://context7.com/giacomo-de-luca/process-sanskrit/llms.txt
Function for retrieving dictionary entries across multiple Sanskrit dictionaries with wildcard support. Defaults to Monier-Williams dictionary when none specified. Supports SQL-style pattern matching for flexible searches.
```python
import process_sanskrit as ps
# Basic dictionary lookup (defaults to Monier-Williams)
entries = ps.dict_search(['pratiprasava', 'saṃskāra'])
# Returns list of [word, components, {dict: {word: [entries]}}] for each input
# Multiple dictionary search
entries = ps.dict_search(['yoga', 'dharma'], 'mw', 'ap90', 'cae', 'gra')
# Searches in Monier-Williams, Apte, Cappeller, and Grassmann dictionaries
# Wildcard search patterns
entries = ps.dict_search(['yoga*']) # All words starting with 'yoga'
# Returns: yogakṣema, yogagata, yogadhāna, yoganidra, etc.
entries = ps.dict_search(['yog_']) # 4-letter words starting with 'yog'
entries = ps.dict_search(['_oga']) # 4-letter words ending with 'oga'
entries = ps.dict_search(['%dhi%']) # SQL-style: words containing 'dhi'
# Available dictionary abbreviations:
# 'mw' - Monier-Williams Sanskrit-English Dictionary (default)
# 'ap90' - Apte Practical Sanskrit-English Dictionary
# 'cae' - Cappeller Sanskrit-English Dictionary
# 'ddsa' - Macdonell Practical Sanskrit Dictionary
```
--------------------------------
### Neural Processing - BYT5 Inference
Source: https://context7.com/giacomo-de-luca/process-sanskrit/llms.txt
Low-level function for running BYT5 model inference for various Sanskrit NLP tasks, including segmentation, lemmatization, and morphosyntactic tagging.
```APIDOC
## Model Inference - BYT5 Neural Processing
### Description
Low-level function for running BYT5 model inference for various Sanskrit NLP tasks.
### Method
POST (Implied, as it's a function call within a library)
### Endpoint
`processBYT5` (Internal function)
### Parameters
- **text** (string or list of strings) - Required - The Sanskrit text(s) to process.
- **mode** (string) - Optional - The processing mode. Available modes: 'detailed' (default), 'roots', 'parts'.
- **dictionaries** (list of strings) - Optional - List of dictionaries to use for analysis (e.g., 'mw', 'ap90').
### Request Example
```python
result = processBYT5('śrutam āgamavijñānaṃ tat sāmānyaviṣayam')
roots = processBYT5('yamaniyamāsanaprāṇāyāmapratyāhāra', mode='roots')
result = processBYT5('cittavṛttinirodhaḥ', mode='detailed', 'mw', 'ap90')
texts = ['atha yogānuśāsanam', 'yogaścittavṛttinirodhaḥ']
results = processBYT5(texts, mode='roots')
parts = processBYT5('dharmārthakāmamokṣāḥ', mode='parts')
```
### Response
#### Success Response (200)
- **result** (string or list or dict) - The processed Sanskrit text, root forms, or compound component mapping, depending on the mode.
#### Response Example
```json
{
"analysis": [
{
"word": "śrutam",
"pos": "noun",
"grammar": ["Nom", "Sg"],
"lemma": "śruta",
"root": "śruta"
}
]
}
```
```
--------------------------------
### Process Sanskrit Text
Source: https://github.com/giacomo-de-luca/process-sanskrit/blob/main/README.md
The core 'process' function takes Sanskrit text, processes it through a pipeline, and returns detailed information about each word or compound.
```APIDOC
## POST /process
### Description
Processes a given Sanskrit text, performing stemming, grammatical tagging, inflection analysis, component breakdown, and dictionary lookups.
### Method
POST
### Endpoint
/process
### Parameters
#### Request Body
- **text** (string) - Required - The Sanskrit text to process.
- **dictionaries** (array of strings) - Optional - Abbreviations of dictionaries to use for lookups (e.g., ['mw', 'ap90']). Defaults to ['mw'].
- **mode** (string) - Optional - Processing mode. 'roots' for stemming only.
### Request Example
```json
{
"text": "pratiprasave",
"dictionaries": ["mw", "ap90", "cae"],
"mode": "full"
}
```
### Response
#### Success Response (200)
- **results** (array of objects) - A list containing detailed information for each processed word or compound.
- **stem** (string) - The stem of the word.
- **tagging** (string) - Grammatical tagging (e.g., 'masculine noun/adjective ending in a').
- **case_inflection** (array of tuples) - Case (for nouns) or inflection (for verbs) (e.g., [('Loc', 'Sg')]).
- **inflection_table** (array of strings) - A list of all possible inflections for the word.
- **original_word** (string) - The original word from the input text.
- **components** (string) - Word components according to Monnier Williams (e.g., 'prati—prasava').
- **dictionary_entries** (object) - Dictionary entries in XML format, keyed by dictionary abbreviation.
#### Response Example
```json
{
"results": [
{
"stem": "pratiprasava",
"tagging": "masculine noun/adjective ending in a",
"case_inflection": [
["Loc", "Sg"]
],
"inflection_table": [
"pratiprasavaḥ",
"pratiprasavau",
"pratiprasavāḥ",
"pratiprasavam",
"pratiprasavau",
"pratiprasavān",
"pratiprasavena",
"pratiprasavābhyām",
"pratiprasavaiḥ",
"pratiprasavāya",
"pratiprasavābhyām",
"pratiprasavebhyaḥ",
"pratiprasavāt",
"pratiprasavābhyām",
"pratiprasavebhyaḥ",
"pratiprasavasya",
"pratiprasavayoḥ",
"pratiprasavānām",
"pratiprasave",
"pratiprasavayoḥ",
"pratiprasaveṣu",
"pratiprasava",
"pratiprasavau",
"pratiprasavāḥ"
],
"original_word": "pratiprasave",
"components": "prati—prasava",
"dictionary_entries": {
"mw": {
"pratiprasava": [
"prati—prasava a See under prati-pra- √ 1. sū.",
"prati-°prasava m. counter-order, suspension of a general prohibition in a particular case, Śaṃkarācārya ; Kātyāyana-śrauta-sūtra , Scholiast or Commentator ; Manvarthamuktāvalī, KullūkaBhaṭṭa\'s commentary on Manu-smṛti ",
" an exception to an exception, Taittirīya-prātiśākhya , Scholiast or Commentator ",
" return to the original state, Yoga-sūtra "
]
}
}
}
]
}
```
```
--------------------------------
### POST /dict_entry - Dictionary Lookup
Source: https://context7.com/giacomo-de-luca/process-sanskrit/llms.txt
Web API endpoint for performing dictionary lookups for a given Sanskrit word across specified dictionaries.
```APIDOC
## Flask API Wrapper - POST /dict_entry
### Description
Web API endpoint for performing dictionary lookups for a given Sanskrit word across specified dictionaries. It accepts a JSON payload with the word and a list of dictionaries.
### Method
POST
### Endpoint
`/dict_entry`
### Parameters
#### Request Body
- **word** (string) - Required - The Sanskrit word to look up.
- **dictionaries** (array of strings) - Optional - A list of dictionary names to search within (e.g., `["mw", "ap90"]`). Defaults to all available dictionaries.
### Request Example
```bash
curl -X POST http://localhost:5000/dict_entry \
-H "Content-Type: application/json" \
-d '{"word": "yoga", "dictionaries": ["mw", "ap90"]}'
```
### Response
#### Success Response (200)
- **dictionary_entries** (array) - A JSON array containing the dictionary entries found for the word.
#### Response Example
```json
[
{
"dictionary": "mw",
"entry": {
"headword": "yoga",
"definitions": [
"union, appointment, the act of joining, yoking, harnessing, putting to, an¿e?",
"meditation, contemplation, abstract meditation, concentration"
]
}
},
{
"dictionary": "ap90",
"entry": {
"headword": "yoga",
"definitions": [
"meditation, contemplation, abstract meditation, concentration"
]
}
}
]
```
```
--------------------------------
### POST /process - Process Sanskrit Text
Source: https://context7.com/giacomo-de-luca/process-sanskrit/llms.txt
Web API endpoint to process raw Sanskrit text using the Process-Sanskrit library's capabilities.
```APIDOC
## Flask API Wrapper - POST /process
### Description
Web API endpoint to process raw Sanskrit text using the Process-Sanskrit library's capabilities. It takes plain text input and returns JSON-formatted processed results.
### Method
POST
### Endpoint
`/process`
### Parameters
#### Request Body
- **text** (string) - Required - The raw Sanskrit text to be processed.
### Request Example
```bash
curl -X POST http://localhost:5000/process \
-H "Content-Type: text/plain" \
-d "yogaścittavṛttinirodhaḥ"
```
### Response
#### Success Response (200)
- **processed_results** (array) - A JSON array containing the processed results for the input text.
#### Response Example
```json
[
{
"word": "yogaścittavṛttinirodhaḥ",
"analysis": [
{
"lemma": "yoga",
"pos": "noun",
"grammar": ["Nom", "Sg"],
"root": "yoga"
},
{
"lemma": "citta",
"pos": "noun",
"grammar": ["Nom", "Sg"],
"root": "citta"
},
{
"lemma": "vṛtti",
"pos": "noun",
"grammar": ["Nom", "Sg"],
"root": "vṛtti"
},
{
"lemma": "nirodha",
"pos": "noun",
"grammar": ["Nom", "Sg"],
"root": "nirodha"
}
]
}
]
```
```
--------------------------------
### POST /batch_process
Source: https://context7.com/giacomo-de-luca/process-sanskrit/llms.txt
Processes a batch of Sanskrit words. It accepts a JSON payload containing a list of words and an optional processing mode.
```APIDOC
## POST /batch_process
### Description
Processes a batch of Sanskrit words. It accepts a JSON payload containing a list of words and an optional processing mode.
### Method
POST
### Endpoint
/batch_process
### Parameters
#### Query Parameters
None
#### Request Body
- **words** (array of strings) - Required - A list of Sanskrit words to process.
- **mode** (string) - Optional - The processing mode (e.g., 'roots'). Defaults to 'roots'.
### Request Example
```json
{
"words": ["yoga", "dharma", "karma"],
"mode": "roots"
}
```
### Response
#### Success Response (200)
- **results** (array) - A list of processing results for each word.
#### Response Example
```json
[
{
"word": "yoga",
"root": "√yuj",
"analysis": "noun,masculine,1st,singular,nominative"
},
{
"word": "dharma",
"root": "√dhṛ",
"analysis": "noun,masculine,1st,singular,nominative"
},
{
"word": "karma",
"root": "√kṛ",
"analysis": "noun,neuter,1st,singular,nominative"
}
]
```
```
--------------------------------
### Analyze Inflected Sanskrit Words for Root Form and Grammar
Source: https://context7.com/giacomo-de-luca/process-sanskrit/llms.txt
Finds the root form and detailed grammatical information for inflected Sanskrit words by querying inflection tables. It automatically handles sandhi variations, prefixes, and alternative spellings (e.g., saṃ/sam). Returns None if no match is found. Supports batch processing.
```python
from process_sanskrit.functions.rootAnyWord import root_any_word
from process_sanskrit.utils.databaseSetup import get_session
session = get_session()
# Analyze inflected noun
result = root_any_word("yogena", session=session)
# Analyze verb form
result = root_any_word("gacchati", session=session)
# Handle sandhi variations
result = root_any_word("rāmeṇa", session=session)
# Prefix handling
result = root_any_word("saṃyoga", session=session)
result = root_any_word("pravṛtti", session=session)
# Alternative spelling handling
result = root_any_word("samyoga", session=session)
# Returns None if no match found
result = root_any_word("nonexistentword", session=session)
# Batch processing
words = ["dharmeṇa", "karmabhiḥ", "jñānāt"]
results = [root_any_word(w, session=session) for w in words]
session.close()
```
--------------------------------
### Search Sanskrit Dictionary Entries
Source: https://github.com/giacomo-de-luca/process-sanskrit/blob/main/README.md
Retrieves dictionary entries for given Sanskrit words. Accepts a list of strings to search and an optional list of dictionary tags to filter results across multiple dictionaries. Input must be in IAST format. Dependencies: process_sanskrit library.
```python
import process_sanskrit as ps
## unlike the process function, the dict_search wants the input in IAST format.
# example usage for Dictionary lookup
ps.dict_search(['pratiprasava', 'saṃskāra'])
# after a list of entries, optionally add dictionary tags to search in multiple dictionaries.
# search in Edgerton Buddhist Hybrid Sanskrit Dictionary
# and Grassmann Wörterbuch zum Rig Veda:
ps.dict_search(['pratiprasava', 'saṃskāra'], 'gra', 'bhs')
```
--------------------------------
### Search Sanskrit Dictionaries with Session Management
Source: https://context7.com/giacomo-de-luca/process-sanskrit/llms.txt
Searches specified Sanskrit dictionaries for a list of words using a database session. It supports automatic expansion to other dictionaries if a word is not found in the primary ones. Session management is crucial for efficient database interactions.
```python
from process_sanskrit.utils.databaseSetup import get_session
session = get_session()
word_list = ['rāma', 'sītā', 'lakṣmaṇa', 'hanumān']
results = ps.dict_search(word_list, 'mw', 'ap90', session=session)
session.close()
# Automatic dictionary expansion
entries = ps.dict_search(['dvandva'], 'mw')
# Alternative spelling handling
entries = ps.dict_search(['saṃskāra'])
entries = ps.dict_search(['samskara'])
```
--------------------------------
### POST /transliterate - Transliteration
Source: https://context7.com/giacomo-de-luca/process-sanskrit/llms.txt
Web API endpoint for transliterating Sanskrit text.
```APIDOC
## Flask API Wrapper - POST /transliterate
### Description
Web API endpoint for transliterating Sanskrit text. It accepts raw text input and returns the transliterated version.
### Method
POST
### Endpoint
`/transliterate`
### Parameters
#### Request Body
- **text** (string) - Required - The Sanskrit text to transliterate.
### Request Example
```bash
curl -X POST http://localhost:5000/transliterate \
-H "Content-Type: text/plain" \
-d "योगश्चित्तवृत्तिनिरोधः"
```
### Response
#### Success Response (200)
- **transliterated_text** (string) - The transliterated Sanskrit text.
#### Response Example
```json
{
"transliterated_text": "yogaścittavṛttinirodhaḥ"
}
```
```
--------------------------------
### Process Sanskrit Text for Stemming Only (Roots Mode)
Source: https://github.com/giacomo-de-luca/process-sanskrit/blob/main/README.md
The 'process' function can be used for basic sandhi/compound splitting and stemming by setting the optional flag `mode='roots'`. This mode returns a list of identified root words from the input text. If there is ambiguity in splitting, the function returns all possible interpretations.
```python
import process_sanskrit as ps
print(ps.process('yamaniyamāsanaprāṇāyāmapratyāhāradhāraṇādhyānasamādhayo', mode='roots'))
```