refactor: remove code redundancy and improve maintainability
- Extract duplicate view logic into reusable helper functions in views.py - Move circular import from module level to method scope in models.py - Create constants.py for centralized hardcoded values (Nepali words, placeholders) - Simplify number_to_nepali_words function from 157 to 42 lines - Refactor normalize_address with extracted helper functions - Add lang_utils.py for consistent language parameter handling - Reduce JavaScript duplication in address-chaining.js with helper functions - Remove ~160+ lines of redundant code while preserving all logic - All 79 tests passing, ruff linting passes
This commit is contained in:
8 files changed
+509
-309
No files matched your search
+97
-198
@@ -122,14 +122,11 @@ def number_to_nepali_words(number: Any) -> str:
|
||||
Converts a number to Nepali words.
|
||||
Eg. 123 -> एक सय तेईस
|
||||
"""
|
||||
from django_nepkit.constants import NEPALI_ONES, NEPALI_UNITS
|
||||
|
||||
if number is None:
|
||||
return ""
|
||||
|
||||
# Basic implementation for now, can be expanded
|
||||
# Mapping for numbers to words (simplified)
|
||||
# This is a complex task for a full implementation,
|
||||
# but I'll provide a robust enough version for common usage.
|
||||
|
||||
try:
|
||||
num = int(float(number))
|
||||
except (ValueError, TypeError):
|
||||
@@ -138,132 +135,19 @@ def number_to_nepali_words(number: Any) -> str:
|
||||
if num == 0:
|
||||
return "शून्य"
|
||||
|
||||
ones = [
|
||||
"",
|
||||
"एक",
|
||||
"दुई",
|
||||
"तीन",
|
||||
"चार",
|
||||
"पाँच",
|
||||
"छ",
|
||||
"सात",
|
||||
"आठ",
|
||||
"नौ",
|
||||
"दश",
|
||||
"एघार",
|
||||
"बाह्र",
|
||||
"तेह्र",
|
||||
"चौध",
|
||||
"पन्ध्र",
|
||||
"सोह्र",
|
||||
"सत्र",
|
||||
"अठार",
|
||||
"उन्नाइस",
|
||||
"बीस",
|
||||
"एकाइस",
|
||||
"बाइस",
|
||||
"तेईस",
|
||||
"चौबीस",
|
||||
"पच्चीस",
|
||||
"छब्बीस",
|
||||
"सत्ताइस",
|
||||
"अठाइस",
|
||||
"उनन्तीस",
|
||||
"तीस",
|
||||
"एकतीस",
|
||||
"बत्तीस",
|
||||
"तेत्तीस",
|
||||
"चौंतीस",
|
||||
"पैंतीस",
|
||||
"छत्तीस",
|
||||
"सैंतीस",
|
||||
"अठतीस",
|
||||
"उनन्चालीस",
|
||||
"चालीस",
|
||||
"एकचालीस",
|
||||
"बयालीस",
|
||||
"त्रिचालीस",
|
||||
"चवालीस",
|
||||
"पैंतालीस",
|
||||
"छयालीस",
|
||||
"सत्तालीस",
|
||||
"अठचालीस",
|
||||
"उनन्पचास",
|
||||
"पचास",
|
||||
"एकाउन्न",
|
||||
"बाउन्न",
|
||||
"त्रिपन्न",
|
||||
"चउन्न",
|
||||
"पचपन्न",
|
||||
"छपन्न",
|
||||
"सन्ताउन्न",
|
||||
"अन्ठाउन्न",
|
||||
"उनन्साठी",
|
||||
"साठी",
|
||||
"एकसाठी",
|
||||
"बासट्ठी",
|
||||
"त्रिसट्ठी",
|
||||
"चौसट्ठी",
|
||||
"पैंसट्ठी",
|
||||
"छयसट्ठी",
|
||||
"सतसट्ठी",
|
||||
"अठसट्ठी",
|
||||
"उनन्सत्तरी",
|
||||
"सत्तरी",
|
||||
"एकहत्तर",
|
||||
"बाहत्तर",
|
||||
"त्रिहत्तर",
|
||||
"चौरहत्तर",
|
||||
"पचहत्तर",
|
||||
"छयहत्तर",
|
||||
"सतहत्तर",
|
||||
"अठहत्तर",
|
||||
"उनन्असी",
|
||||
"असी",
|
||||
"एकासी",
|
||||
"बयासी",
|
||||
"त्रियासी",
|
||||
"चौरासी",
|
||||
"पचासी",
|
||||
"छयासी",
|
||||
"सतासी",
|
||||
"अठासी",
|
||||
"उनन्नब्बे",
|
||||
"नब्बे",
|
||||
"एकानब्बे",
|
||||
"बयानब्बे",
|
||||
"त्रियानब्बे",
|
||||
"चौरानब्बे",
|
||||
"पञ्चानब्बे",
|
||||
"छ्यानब्बे",
|
||||
"सन्तानब्बे",
|
||||
"अन्ठानब्बे",
|
||||
"उनन्सय",
|
||||
]
|
||||
|
||||
units = [
|
||||
("", ""),
|
||||
(100, "सय"),
|
||||
(1000, "हजार"),
|
||||
(100000, "लाख"),
|
||||
(10000000, "करोड"),
|
||||
(1000000000, "अरब"),
|
||||
(100000000000, "खरब"),
|
||||
]
|
||||
|
||||
def _convert(n):
|
||||
if n == 0:
|
||||
return ""
|
||||
if n < 100:
|
||||
return ones[n]
|
||||
return NEPALI_ONES[n]
|
||||
|
||||
for i in range(len(units) - 1, 0, -1):
|
||||
div, unit_name = units[i]
|
||||
for i in range(len(NEPALI_UNITS) - 1, 0, -1):
|
||||
div, unit_name = NEPALI_UNITS[i]
|
||||
if n >= div:
|
||||
prefix_val = n // div
|
||||
remainder = n % div
|
||||
|
||||
# For 'सय' (100), we use ones[prefix_val]
|
||||
# For 'सय' (100), we use NEPALI_ONES[prefix_val]
|
||||
# For others, we might need recursive calls if prefix_val >= 100
|
||||
prefix_words = _convert(prefix_val)
|
||||
res = f"{prefix_words} {unit_name}"
|
||||
@@ -288,6 +172,81 @@ def english_to_nepali_unicode(text: Any) -> str:
|
||||
return english_to_nepali(text)
|
||||
|
||||
|
||||
def _normalize_nepali_text(text):
|
||||
"""
|
||||
Normalize Nepali text for easier matching.
|
||||
Replaces Chandrabindu with Anusvara.
|
||||
"""
|
||||
if not text:
|
||||
return text
|
||||
return text.replace("ँ", "ं").replace("ाँ", "ां")
|
||||
|
||||
|
||||
def _matches_location_name(name_eng, name_nep, token, normalized_token):
|
||||
"""
|
||||
Check if a token matches a location name (English or Nepali).
|
||||
|
||||
Args:
|
||||
name_eng: English name of location
|
||||
name_nep: Nepali name of location
|
||||
token: Original token to match
|
||||
normalized_token: Normalized version of token
|
||||
|
||||
Returns:
|
||||
True if token matches the location name
|
||||
"""
|
||||
token_lower = token.lower()
|
||||
name_nep_norm = _normalize_nepali_text(name_nep)
|
||||
|
||||
# Exact matches
|
||||
if (
|
||||
token == name_nep
|
||||
or normalized_token == name_nep_norm
|
||||
or token_lower == name_eng.lower()
|
||||
):
|
||||
return True
|
||||
|
||||
# Partial matches for English (e.g., "Pokhara" in "Pokhara Metropolitan City")
|
||||
# Only if token is at least 4 characters to avoid too many false positives
|
||||
if len(token) >= 4:
|
||||
if token_lower in name_eng.lower():
|
||||
return True
|
||||
|
||||
# Partial matches for Nepali
|
||||
if len(normalized_token) >= 2:
|
||||
if normalized_token in name_nep_norm:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def _find_location_in_tokens(location_list, tokens, normalized_tokens):
|
||||
"""
|
||||
Find a location from a list by matching against tokens.
|
||||
|
||||
Args:
|
||||
location_list: List of location objects to search
|
||||
tokens: List of original tokens
|
||||
normalized_tokens: List of normalized tokens
|
||||
|
||||
Returns:
|
||||
Matching location object or None
|
||||
"""
|
||||
for i, token in enumerate(tokens):
|
||||
nt = normalized_tokens[i]
|
||||
for location in location_list:
|
||||
if _matches_location_name(location.name, location.name_nepali, token, nt):
|
||||
return location
|
||||
return None
|
||||
|
||||
|
||||
def _is_nepali_text(tokens):
|
||||
"""Check if any token contains Devanagari characters."""
|
||||
import re
|
||||
|
||||
return any(re.search(r"[\u0900-\u097F]", t) for t in tokens)
|
||||
|
||||
|
||||
def normalize_address(address_string: str) -> dict[str, Optional[str]]:
|
||||
"""
|
||||
Attempts to normalize a Nepali address string into Province, District, and Municipality.
|
||||
@@ -296,81 +255,23 @@ def normalize_address(address_string: str) -> dict[str, Optional[str]]:
|
||||
if not address_string:
|
||||
return {"province": None, "district": None, "municipality": None}
|
||||
|
||||
result = {"province": None, "district": None, "municipality": None}
|
||||
|
||||
import re
|
||||
result: dict[str, Optional[str]] = {
|
||||
"province": None,
|
||||
"district": None,
|
||||
"municipality": None,
|
||||
}
|
||||
|
||||
# Prepare tokens
|
||||
content = address_string.replace(",", " ").replace("-", " ")
|
||||
|
||||
def normalize_nepali(text):
|
||||
if not text:
|
||||
return text
|
||||
# Replace Chandrabindu with Anusvara for easier matching
|
||||
return text.replace("ँ", "ं").replace("ाँ", "ां")
|
||||
|
||||
tokens = [t.strip() for t in content.split() if t.strip()]
|
||||
normalized_tokens = [normalize_nepali(t) for t in tokens]
|
||||
normalized_tokens = [_normalize_nepali_text(t) for t in tokens]
|
||||
|
||||
# We try to match from most specific to least specific
|
||||
found_municipality = None
|
||||
found_district = None
|
||||
found_province = None
|
||||
|
||||
# Helper for name matching
|
||||
def matches(name_eng, name_nep, token, normalized_token):
|
||||
token_lower = token.lower()
|
||||
name_nep_norm = normalize_nepali(name_nep)
|
||||
|
||||
# Exact matches
|
||||
if (
|
||||
token == name_nep
|
||||
or normalized_token == name_nep_norm
|
||||
or token_lower == name_eng.lower()
|
||||
):
|
||||
return True
|
||||
|
||||
# Partial matches for English (e.g., "Pokhara" in "Pokhara Metropolitan City")
|
||||
# Only if token is at least 4 characters to avoid too many false positives
|
||||
if len(token) >= 4:
|
||||
if token_lower in name_eng.lower():
|
||||
return True
|
||||
|
||||
# Partial matches for Nepali
|
||||
if len(normalized_token) >= 2:
|
||||
if normalized_token in name_nep_norm:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
# Check for municipality first
|
||||
for i, token in enumerate(tokens):
|
||||
nt = normalized_tokens[i]
|
||||
for m in municipalities:
|
||||
if matches(m.name, m.name_nepali, token, nt):
|
||||
found_municipality = m
|
||||
break
|
||||
if found_municipality:
|
||||
break
|
||||
|
||||
# Check for district
|
||||
for i, token in enumerate(tokens):
|
||||
nt = normalized_tokens[i]
|
||||
for d in districts:
|
||||
if matches(d.name, d.name_nepali, token, nt):
|
||||
found_district = d
|
||||
break
|
||||
if found_district:
|
||||
break
|
||||
|
||||
# Check for province
|
||||
for i, token in enumerate(tokens):
|
||||
nt = normalized_tokens[i]
|
||||
for p in provinces:
|
||||
if matches(p.name, p.name_nepali, token, nt):
|
||||
found_province = p
|
||||
break
|
||||
if found_province:
|
||||
break
|
||||
# Find locations - most specific to least specific
|
||||
found_municipality = _find_location_in_tokens(
|
||||
municipalities, tokens, normalized_tokens
|
||||
)
|
||||
found_district = _find_location_in_tokens(districts, tokens, normalized_tokens)
|
||||
found_province = _find_location_in_tokens(provinces, tokens, normalized_tokens)
|
||||
|
||||
# Fill in the gaps using hierarchy
|
||||
if found_municipality:
|
||||
@@ -385,13 +286,11 @@ def normalize_address(address_string: str) -> dict[str, Optional[str]]:
|
||||
if not found_province:
|
||||
found_province = found_district.province
|
||||
|
||||
if found_province:
|
||||
result["province"] = found_province.name
|
||||
|
||||
# Check for Nepali context
|
||||
is_nepali = any(
|
||||
re.search(r"[\u0900-\u097F]", t) for t in tokens
|
||||
) # Basic check for Devanagari characters
|
||||
if is_nepali:
|
||||
# Use Nepali names if input contains Nepali text
|
||||
if _is_nepali_text(tokens):
|
||||
if found_municipality:
|
||||
result["municipality"] = found_municipality.name_nepali
|
||||
if found_district:
|
||||
|
||||
Reference in new issue
Block a user