sindhi-ngram / app_backend.py
hellosindh
Optimize concordance query on HF Space by removing expensive ORDER BY
e09c53c
Raw History Blame Contribute Delete
55.6 kB
""" 3_web_app.py Sindhi Books Ngram Viewer (سنڌي ڪتابن جي اين گرام) Complete Web System with: - Main Search & Ngram Chart (Google Ngram Viewer style) - Corpus Selection: Books (ڪتاب), Newspaper Articles (اخبارن جا مضمون), Pamphlets (پمفليٽ), or Both/Combined (گڏيل) - Multi-word Concordance Filtering (word-by-word filter pills) - Section Attributions (e.g. مھاڳ: نذار قباني) - Public Book Checker & Live Ngram Comparison (/check-book) - Public Book & Article Submission for Admin Review - Admin Publication Ingestion with Multi-box Sections & Document Types - Author Chips / Tag Input (press comma or enter) - Submissions Review & Approval Pipeline - Database Reset for Fresh Start """ import os import sys import re import json import sqlite3 import hashlib import html from typing import Dict, List, Any from datetime import datetime import collections from flask import Flask, request, jsonify, render_template_string, send_from_directory, redirect # Ensure UTF-8 stdout encoding for Windows if sys.platform == 'win32': try: sys.stdout.reconfigure(encoding='utf-8') except Exception: pass import sindhi_nlp import importlib process_books_module = importlib.import_module("1_process_books") import author_analytics from templates import ( COMMON_CSS, MAIN_PAGE_TEMPLATE, ABOUT_PAGE_TEMPLATE, TOP50_PAGE_TEMPLATE, USAGE_PAGE_TEMPLATE ) # Hardcoded max cutoff date: September 30, 2026 HARDCODED_CUTOFF_DATE = "2026-09-30" LAST_UPDATE_EN = "September 30, 2026" LAST_UPDATE_SD = "30 سيپٽمبر 2026ع" MAX_ALLOWED_YEAR = 2026 def resolve_database(): local_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ngram_database.db") if os.path.exists(local_path): return local_path try: from huggingface_hub import hf_hub_download token = os.environ.get("HF_TOKEN") print("Fetching ngram_database.db from dataset repo...") return hf_hub_download( repo_id="hellosindh/sindhi-ngram-database", filename="ngram_database.db", repo_type="dataset", token=token, ) except Exception as e: print(f"Error fetching DB from Hub: {e}") return local_path DB_FILE = resolve_database() app = Flask(__name__) # Enable CORS for all API routes so external frontends (hellosindh.com) can call directly @app.after_request def add_cors_headers(response): response.headers["Access-Control-Allow-Origin"] = "*" response.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS, HEAD" response.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization, X-Requested-With" return response @app.route('/api/<path:path>', methods=['OPTIONS']) def options_handler(path): return ('', 204) # Ensure DB schema on startup try: _conn = process_books_module.init_database(DB_FILE) _conn.close() except Exception as e: print(f"DB Init warning: {e}") def get_db(): conn = sqlite3.connect(DB_FILE) conn.row_factory = sqlite3.Row return conn # In-memory cache for year totals to make ngram lookups instant YEAR_TOTALS_CACHE = {} # (year, doc_type, n_size) -> total_count ALL_DB_YEARS = [] CACHED_DISTINCT_NGRAMS = 10744813 def refresh_year_totals_cache(): global YEAR_TOTALS_CACHE, ALL_DB_YEARS, CACHED_DISTINCT_NGRAMS try: conn = get_db() cur = conn.cursor() cur.execute("SELECT year, doc_type, n_size, SUM(total_count) as tot FROM year_totals GROUP BY year, doc_type, n_size") new_cache = {} years_set = set() for r in cur.fetchall(): new_cache[(r["year"], r["doc_type"] or "book", r["n_size"])] = r["tot"] years_set.add(r["year"]) YEAR_TOTALS_CACHE = new_cache ALL_DB_YEARS = sorted([y for y in years_set if y <= 2026]) conn.close() except Exception as e: print("Cache refresh warning:", e) refresh_year_totals_cache() def apply_smoothing(yearly_data: Dict[int, float], years: List[int], smoothing: int) -> Dict[int, float]: if smoothing <= 0: return yearly_data smoothed = {} for y in years: window_vals = [] for offset in range(-smoothing, smoothing + 1): check_yr = y + offset if check_yr in yearly_data: window_vals.append(yearly_data[check_yr]) if window_vals: smoothed[y] = sum(window_vals) / len(window_vals) else: smoothed[y] = 0.0 return smoothed # ========================================== # Frontend Page Routes # ========================================== @app.route("/") def page_index(): return render_template_string(MAIN_PAGE_TEMPLATE) @app.route("/top50") @app.route("/top-50") @app.route("/top100") @app.route("/top-100") @app.route("/trend") @app.route("/trends") def page_top50(): return render_template_string(TOP50_PAGE_TEMPLATE) @app.route("/usage") @app.route("/guide") @app.route("/istimal") def page_usage(): return render_template_string(USAGE_PAGE_TEMPLATE) @app.route("/about") def page_about(): return render_template_string(ABOUT_PAGE_TEMPLATE) @app.route("/check-book") @app.route("/admin") def page_redirect_home(): return redirect("/") @app.route("/asset/<path:filename>") def serve_asset(filename): return send_from_directory("asset", filename) @app.route("/fonts/<path:filename>") def serve_fonts(filename): return send_from_directory("fonts", filename) # ========================================== # Public APIs # ========================================== @app.route("/api/stats") @app.route("/stats") def api_stats(): # Load from precomputed corpus_stats.json if present cs_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "corpus_stats.json") if os.path.exists(cs_path): try: with open(cs_path, "r", encoding="utf-8") as f: data = json.load(f) return jsonify(data) except Exception: pass conn = get_db() cur = conn.cursor() cur.execute("SELECT SUM(total_words) FROM books WHERE year <= 2026") total_words = cur.fetchone()[0] or 0 cur.execute("SELECT COUNT(*) FROM books WHERE doc_type = 'book' AND year <= 2026") total_books = cur.fetchone()[0] or 0 cur.execute("SELECT COUNT(*) FROM books WHERE doc_type = 'article' AND year <= 2026") total_articles = cur.fetchone()[0] or 0 cur.execute("SELECT COUNT(*) FROM books WHERE doc_type = 'pamphlet' AND year <= 2026") total_pamphlets = cur.fetchone()[0] or 0 conn.close() return jsonify({ "status": "ok", "last_update": LAST_UPDATE_EN, "last_update_sd": LAST_UPDATE_SD, "cutoff_date": HARDCODED_CUTOFF_DATE, "total_words": total_words, "total_books": total_books, "total_articles": total_articles, "total_pamphlets": total_pamphlets, "total_ngrams": CACHED_DISTINCT_NGRAMS, "distinct_ngrams": CACHED_DISTINCT_NGRAMS }) YEARLY_STATS_FILE = os.path.join(os.path.dirname(__file__), "yearly_word_stats.json") CACHED_YEARLY_WORD_STATS = None RAW_EXCLUDED_COMMON_WORDS = """ پڻ مونکي جي ۾ تہ جا جن مان مون تي ھئي ھو ھوندا ھوندي ھيو ئي بہ ٿي ٿيو ٿيا ٿيندا ٿيندو ٿيندي ھوندو اسان اسين ان پر سان کان کائنس پنھنجي منھنجي تنھنجي توھان تون توھانجي اوھان اوھانجي ڪري ڪريو ھڪ ٻہ ٽي ھنن ھن آھن لاءِ رھيو رھيا ويو ويا ويندا ويندو ويندي ڪجھہ پئي گهڻو پيا پيو ھئا اچي وڃي وڃن اچن آھي کي ۽ جو نہ ٿو سندس جنھن ڪيو پوءِ ڪرڻ ٿا پاڻ اھو انھي يا سندن انھن جون ڪنھن کيس طور ڪئي ڪو جيئن گڏ ھي ٿئي واري تائين جڏھن ھر ٻين ڪونہ جيڪي اھي اھا وٽ ڇا ڪر ٿيڻ وارو ڪن ڪا وري ھوءَ انھيءَ وڏي of وڏو and ملي سو ڏي کين کڻي وٺي هيءُ in """ EXCLUDED_COMMON_WORDS_MAP = {} for _w in [w.strip() for w in RAW_EXCLUDED_COMMON_WORDS.split() if w.strip()]: _wnorm = sindhi_nlp.normalize_sindhi(_w, strip_diacritics=True, normalize_heh_variants=True) if _wnorm not in EXCLUDED_COMMON_WORDS_MAP: EXCLUDED_COMMON_WORDS_MAP[_wnorm] = _w EXCLUDED_COMMON_WORDS_MAP[_w] = _w EXCLUDED_COMMON_WORDS_SET = set(EXCLUDED_COMMON_WORDS_MAP.keys()) def compute_and_cache_yearly_stats(): global CACHED_YEARLY_WORD_STATS import unicodedata def is_valid_sindhi_word(w: str) -> bool: if not w or re.search(r'[a-zA-Z]', w): return False for ch in w: if ('\u0600' <= ch <= '\u06FF') or ('\u0750' <= ch <= '\u077F') or ('\uFB50' <= ch <= '\uFDFF'): if unicodedata.category(ch) != 'Mn' and ch != '\u0640': return True return False def count_letters(word): c = 0 for ch in word: if unicodedata.category(ch) != 'Mn' and ch != '\u0640' and (ch.isalpha() or ('\u0600' <= ch <= '\u06FF')): c += 1 return c conn = get_db() cur = conn.cursor() cur.execute("SELECT year, COUNT(*), SUM(total_words) FROM books GROUP BY year") book_counts = {r[0]: {'books': r[1], 'words': r[2] or 0} for r in cur.fetchall()} cur.execute("SELECT DISTINCT year FROM year_totals WHERE n_size=1 ORDER BY year ASC") chrono_years = [r[0] for r in cur.fetchall()] cur.execute("SELECT year, ngram, count FROM ngram_counts WHERE n_size = 1") rows = cur.fetchall() yearly_metrics = {yr: {'words': 0, 'chars': 0} for yr in chrono_years} total_all_words = 0 total_all_chars = 0 words_by_year_counts = collections.defaultdict(lambda: collections.defaultdict(int)) word_display_counts = collections.defaultdict(lambda: collections.defaultdict(int)) excluded_counts = {norm_w: collections.defaultdict(int) for norm_w in EXCLUDED_COMMON_WORDS_SET} for yr, ngram, cnt in rows: if yr in yearly_metrics: letters = count_letters(ngram) yearly_metrics[yr]['words'] += cnt yearly_metrics[yr]['chars'] += letters * cnt total_all_words += cnt total_all_chars += letters * cnt # Exclude English words and non-Sindhi script from top 100 if not is_valid_sindhi_word(ngram): continue norm_ng = sindhi_nlp.normalize_sindhi(ngram, strip_diacritics=True, normalize_heh_variants=True) if norm_ng in EXCLUDED_COMMON_WORDS_SET or ngram in EXCLUDED_COMMON_WORDS_SET: target_key = norm_ng if norm_ng in EXCLUDED_COMMON_WORDS_SET else ngram excluded_counts[target_key][yr] += cnt elif letters > 0: words_by_year_counts[yr][norm_ng] += cnt word_display_counts[norm_ng][ngram] += cnt word_display_form = {} for norm_w, disp_map in word_display_counts.items(): sorted_forms = sorted(disp_map.items(), key=lambda x: x[1], reverse=True) word_display_form[norm_w] = sorted_forms[0][0] year_top_100 = {} for yr in chrono_years: counts_map = words_by_year_counts.get(yr, {}) raw_list = [(word_display_form.get(nw, nw), cnt) for nw, cnt in counts_map.items()] raw_list.sort(key=lambda x: x[1], reverse=True) top100 = raw_list[:100] year_top_100[yr] = {w: (idx + 1, cnt) for idx, (w, cnt) in enumerate(top100)} top_words_by_year = {} for i, yr in enumerate(chrono_years): prev_yr = chrono_years[i-1] if i > 0 else None words_list = [] sorted_words = sorted(year_top_100[yr].items(), key=lambda x: x[1][0])[:100] for w, (rank, cnt) in sorted_words: w_letters = count_letters(w) if prev_yr and w in year_top_100[prev_yr]: prev_rank = year_top_100[prev_yr][w][0] change = prev_rank - rank if change > 0: status = 'up' elif change < 0: status = 'down' else: status = 'same' else: prev_rank = None change = None status = 'new' words_list.append({ 'rank': rank, 'word': w, 'count': cnt, 'letters': w_letters, 'prev_rank': prev_rank, 'change': change, 'status': status }) top_words_by_year[yr] = words_list yearly_summary = [] for yr in sorted(chrono_years, reverse=True): w = yearly_metrics[yr]['words'] ch = yearly_metrics[yr]['chars'] avg_len = round(ch / w) if w > 0 else 0 b_count = book_counts.get(yr, {}).get('books', 0) yearly_summary.append({ 'year': yr, 'words': w, 'chars': ch, 'avg_word_length': avg_len, 'books_count': b_count }) overall_avg_len = round(total_all_chars / total_all_words) if total_all_words > 0 else 0 # Calculate top years for each excluded common word excluded_summary = [] for norm_w, orig_w in EXCLUDED_COMMON_WORDS_MAP.items(): yc = excluded_counts.get(norm_w, {}) sorted_yrs = sorted(yc.items(), key=lambda x: x[1], reverse=True) top_years = [y for y, _ in sorted_yrs[:3]] excluded_summary.append({ 'word': orig_w, 'top_years': top_years }) conn.close() result = { 'total_words': total_all_words, 'total_chars': total_all_chars, 'overall_avg_word_length': overall_avg_len, 'years': sorted(chrono_years, reverse=True), 'yearly_summary': yearly_summary, 'top_words_by_year': top_words_by_year, 'excluded_common_words': excluded_summary } try: with open(YEARLY_STATS_FILE, 'w', encoding='utf-8') as f: json.dump(result, f, ensure_ascii=False) except Exception as e: print("Warning saving yearly stats file:", e) CACHED_YEARLY_WORD_STATS = result return result def get_yearly_word_stats(force_refresh=False): global CACHED_YEARLY_WORD_STATS if CACHED_YEARLY_WORD_STATS is not None and not force_refresh: return CACHED_YEARLY_WORD_STATS if os.path.exists(YEARLY_STATS_FILE) and not force_refresh: try: with open(YEARLY_STATS_FILE, 'r', encoding='utf-8') as f: CACHED_YEARLY_WORD_STATS = json.load(f) return CACHED_YEARLY_WORD_STATS except Exception as e: print("Warning reading yearly stats file:", e) return compute_and_cache_yearly_stats() @app.route("/api/yearly-word-stats") @app.route("/api/yearly_word_stats") @app.route("/api/top50") @app.route("/api/top-50") @app.route("/api/top100") @app.route("/api/top-100") def api_yearly_word_stats(): data = get_yearly_word_stats() if data: return jsonify({"status": "ok", **data}) return jsonify({"status": "error", "message": "ڊيٽا لوڊ نه ٿي سگهي"}), 500 WORD_TOP_YEARS_INDEX = None WORD_NORM_TOP_YEARS_INDEX = None def get_word_top_years_index(): global WORD_TOP_YEARS_INDEX, WORD_NORM_TOP_YEARS_INDEX if WORD_TOP_YEARS_INDEX is not None: return WORD_TOP_YEARS_INDEX, WORD_NORM_TOP_YEARS_INDEX stats = get_yearly_word_stats() top_words_by_year = stats.get('top_words_by_year', {}) w_index = {} wn_index = {} for yr_str, words in top_words_by_year.items(): try: yr = int(yr_str) except Exception: continue for item in words: w = item.get('word', '').strip() if not w: continue if w not in w_index: w_index[w] = [] if yr not in w_index[w]: w_index[w].append(yr) wn = sindhi_nlp.normalize_sindhi(w, strip_diacritics=True, normalize_heh_variants=True).strip() if wn not in wn_index: wn_index[wn] = [] if yr not in wn_index[wn]: wn_index[wn].append(yr) for k in w_index: w_index[k].sort() for k in wn_index: wn_index[k].sort() WORD_TOP_YEARS_INDEX = w_index WORD_NORM_TOP_YEARS_INDEX = wn_index return WORD_TOP_YEARS_INDEX, WORD_NORM_TOP_YEARS_INDEX def get_top_50_insights_for_query(raw_query: str, heh_norm: bool = True) -> list: if not raw_query: return [] w_index, wn_index = get_word_top_years_index() terms = [t.strip().replace("*", "") for t in re.split(r'[,،+|]+', raw_query) if t.strip()] insights = [] seen_words = set() for raw_term in terms: clean_w = raw_term.strip() if not clean_w or clean_w in seen_words: continue seen_words.add(clean_w) years = w_index.get(clean_w) if not years: clean_wn = sindhi_nlp.normalize_sindhi(clean_w, strip_diacritics=True, normalize_heh_variants=True).strip() years = wn_index.get(clean_wn) if not years: continue years = sorted(list(set(years))) if len(years) >= 12: msg = f"{clean_w} سنڌي ٻولي جو عام لفظ آھي، جيڪو تقريبن ھر سال ٽاپ 100 جي فھرست ۾ موجود آھي." target_year = years[-1] elif len(years) == 1: msg = f"{clean_w} {years[0]}ع جي ٽاپ 100 لفظن ۾ شامل ھو." target_year = years[0] elif len(years) == 2: msg = f"{clean_w} {years[0]} ۽ {years[1]}ع جي ٽاپ 100 لفظن ۾ شامل ھو." target_year = years[1] else: formatted_years = "، ".join(str(y) for y in years[:-1]) + f" ۽ {years[-1]}ع" msg = f"{clean_w} {formatted_years} جي ٽاپ 100 لفظن ۾ شامل ھو." target_year = years[-1] insights.append({ "word": clean_w, "years": years, "target_year": target_year, "message": msg, "anchor_url": f"/top100?year={target_year}&word={clean_w}" }) return insights @app.route("/api/ngram") @app.route("/ngram") def api_ngram(): raw_query = request.args.get("q", "").strip() start_year = request.args.get("start_year", type=int) end_year = request.args.get("end_year", type=int) smoothing = request.args.get("smoothing", default=3, type=int) corpus = request.args.get("corpus", default="all").strip().lower() # 'all', 'article', 'book', 'pamphlet' normalize = request.args.get("normalize", default="true").lower() == "true" heh_norm = request.args.get("heh_norm", default="true").lower() == "true" combine = request.args.get("combine", default="false").lower() == "true" auto_years = request.args.get("auto_years", default="false").lower() == "true" if not raw_query: return jsonify({"status": "error", "message": "Query cannot be empty"}) # Strict user terms - no auto alias expansion (as requested) final_terms = [t.strip() for t in re.split(r'[,،]+', raw_query) if t.strip()] db_min = ALL_DB_YEARS[0] if ALL_DB_YEARS else 1792 db_max = min(ALL_DB_YEARS[-1] if ALL_DB_YEARS else 2026, 2026) all_years = list(range(db_min, db_max + 1)) conn = get_db() cur = conn.cursor() # Wildcard expansion (* support) expanded_terms = [] for term in final_terms: if '*' in term: clean = term.replace('*', '').strip() if clean: clean_norm = sindhi_nlp.normalize_sindhi(clean, strip_diacritics=True) clean_heh = sindhi_nlp.normalize_sindhi(clean, strip_diacritics=True, normalize_heh_variants=True) search_prefix = clean_heh if heh_norm else clean_norm target_col = "ngram_heh_norm" if heh_norm else "ngram_norm" n_sz = min(len(clean.split()) + 1, 3) if corpus in ["all", "both"]: sql = f""" SELECT ngram, SUM(count) as total_cnt FROM ngram_counts WHERE {target_col} >= ? AND {target_col} <= ? AND n_size = ? GROUP BY ngram ORDER BY total_cnt DESC LIMIT 10 """ cur.execute(sql, (search_prefix + " ", search_prefix + "\uffff", n_sz)) else: sql = f""" SELECT ngram, SUM(count) as total_cnt FROM ngram_counts WHERE {target_col} >= ? AND {target_col} <= ? AND doc_type = ? AND n_size = ? GROUP BY ngram ORDER BY total_cnt DESC LIMIT 10 """ cur.execute(sql, (search_prefix + " ", search_prefix + "\uffff", corpus, n_sz)) matches = [r["ngram"] for r in cur.fetchall()] if matches: expanded_terms.extend(matches) else: expanded_terms.append(clean) else: expanded_terms.append(term) term_data_list = [] all_active_years = [] for term in expanded_terms: # Check if term has pipe '|' for merged sub-terms (e.g. "جي ايم سيد|جي ايم شاھ") sub_terms = [st.strip() for st in term.split('|') if st.strip()] if not sub_terms: continue merged_counts = {y: 0 for y in all_years} merged_raw_pcts = {y: 0.0 for y in all_years} total_sub_occ = 0 for st in sub_terms: words = st.split() n_size = len(words) if n_size == 0: continue # In-memory lookup for year totals (0ms) y_totals = {} for y in all_years: if corpus in ["all", "both"]: tot = sum(v for k, v in YEAR_TOTALS_CACHE.items() if k[0] == y and k[2] == n_size) else: tot = YEAR_TOTALS_CACHE.get((y, corpus, n_size), 0) if tot > 0: y_totals[y] = tot # Pick normalized column col_name = "ngram_heh_norm" if heh_norm else ("ngram_norm" if normalize else "ngram") st_search = sindhi_nlp.normalize_sindhi(st, strip_diacritics=normalize, normalize_heh_variants=heh_norm) if (normalize or heh_norm) else st # Generate search variants for database compatibility (e.g. انھي vs انھيء) search_variants = [st_search] if normalize or heh_norm: if st_search.endswith('ي'): search_variants.append(st_search + 'ء') elif st_search.endswith('يء'): search_variants.append(st_search[:-1]) if st_search in ['هن', 'ھن', 'ڪنهن', 'ڪنھن']: search_variants.append(st_search + 'ء') st_counts = {} for var in search_variants: if corpus in ["all", "both"]: cur.execute(f"SELECT year, SUM(count) as cnt FROM ngram_counts WHERE {col_name} = ? AND n_size = ? GROUP BY year", (var, n_size)) else: cur.execute(f"SELECT year, SUM(count) as cnt FROM ngram_counts WHERE {col_name} = ? AND doc_type = ? AND n_size = ? GROUP BY year", (var, corpus, n_size)) for r in cur.fetchall(): y = r["year"] st_counts[y] = st_counts.get(y, 0) + r["cnt"] for yr, cnt in st_counts.items(): if cnt > 0: all_active_years.append(yr) merged_counts[yr] = merged_counts.get(yr, 0) + cnt total_sub_occ += cnt for y in all_years: c = st_counts.get(y, 0) tot = y_totals.get(y, 0) if tot > 0 and c > 0: merged_raw_pcts[y] += (c / tot * 100.0) term_data_list.append({ "term": term, "y_counts": merged_counts, "y_raw_pcts": merged_raw_pcts, "total_occurrences": total_sub_occ }) # Dynamic start/end year logic min_possible = ALL_DB_YEARS[0] if ALL_DB_YEARS else 1792 max_possible = ALL_DB_YEARS[-1] if ALL_DB_YEARS else 2025 suggested_start_year = None suggested_end_year = max_possible if all_active_years: first_active = min(all_active_years) suggested_start_year = first_active suggested_end_year = max_possible if auto_years: effective_start_year = suggested_start_year if suggested_start_year is not None else (start_year if start_year is not None else 1980) effective_end_year = suggested_end_year if suggested_end_year is not None else (end_year if end_year is not None else 2026) else: effective_start_year = start_year if start_year is not None else 1980 effective_end_year = end_year if end_year is not None else 2026 if effective_end_year < effective_start_year: effective_end_year = max(effective_start_year, max_possible) timeline = list(range(effective_start_year, effective_end_year + 1)) if effective_end_year >= effective_start_year else all_years series = [] for t_item in term_data_list: term = t_item["term"] y_counts = t_item["y_counts"] y_raw_pcts = t_item["y_raw_pcts"] raw_pcts = {y: y_raw_pcts.get(y, 0.0) for y in timeline} smooth_pcts = apply_smoothing(raw_pcts, timeline, smoothing) series.append({ "term": term, "counts": {y: y_counts.get(y, 0) for y in timeline}, "frequencies": smooth_pcts, "raw_frequencies": raw_pcts, "total_occurrences": t_item["total_occurrences"] }) # Combine frequencies option if combine and len(series) > 1: combined_counts = {} combined_raw_pcts = {} for y in timeline: combined_counts[y] = sum(s["counts"].get(y, 0) for s in series) combined_raw_pcts[y] = sum(s["raw_frequencies"].get(y, 0.0) for s in series) combined_smooth = apply_smoothing(combined_raw_pcts, timeline, smoothing) series = [{ "term": " + ".join([s["term"] for s in series]) + " (گڏيل)", "counts": combined_counts, "frequencies": combined_smooth, "raw_frequencies": combined_raw_pcts, "total_occurrences": sum(combined_counts.values()), "is_combined": True }] conn.close() ai_insights = get_top_50_insights_for_query(raw_query, heh_norm=heh_norm) return jsonify({ "status": "ok", "years": timeline, "series": series, "terms": [s["term"] for s in series], "start_year": effective_start_year, "end_year": effective_end_year, "suggested_start_year": suggested_start_year, "suggested_end_year": suggested_end_year, "ai_insights": ai_insights }) def contains_exact_word(sentence: str, term: str, heh_norm: bool = True) -> bool: """Checks if `term` exists as a complete, independent word/phrase in `sentence`.""" if not sentence or not term: return False norm_term = sindhi_nlp.normalize_sindhi(term, strip_diacritics=True, normalize_heh_variants=heh_norm).strip() norm_sent = sindhi_nlp.normalize_sindhi(sentence, strip_diacritics=True, normalize_heh_variants=heh_norm) pattern = r'(?<!\w)' + re.escape(norm_term) + r'(?!\w)' return bool(re.search(pattern, norm_sent)) @app.route("/api/snippets") @app.route("/snippets") def api_snippets(): raw_query = request.args.get("q", "").strip() year = request.args.get("year", type=int) limit = request.args.get("limit", default=40, type=int) corpus = request.args.get("corpus", default="all").strip().lower() heh_norm = request.args.get("heh_norm", default="true").lower() == "true" if not raw_query: return jsonify({"status": "ok", "snippets": []}) terms = [t.strip().replace("*", "").strip() for t in re.split(r'[,،+|]+', raw_query) if t.strip()] conn = get_db() cur = conn.cursor() snippets = [] seen_sentences = set() per_term_limit = max(1, limit) for t in terms: t_norm = sindhi_nlp.normalize_sindhi(t, strip_diacritics=True, normalize_heh_variants=heh_norm) col_sent = "c.sentence_heh_norm" if heh_norm else "c.sentence_norm" conditions = [f"{col_sent} LIKE ?"] params = [f"%{t_norm}%"] if year: conditions.append("c.year = ?") params.append(year) if corpus not in ["all", "both"]: conditions.append("c.doc_type = ?") params.append(corpus) where_clause = " AND ".join(conditions) # Fetch extra candidate rows to account for whole-word filtering sql = f""" SELECT c.sentence, c.year, b.title, b.author, b.doc_type, b.source_name FROM concordance c JOIN books b ON c.book_id = b.id WHERE {where_clause} LIMIT ? """ cur.execute(sql, params + [max(per_term_limit * 5, 100)]) term_count = 0 for row in cur.fetchall(): s = row["sentence"] # Enforce exact complete word matching: searching for "عباس" will NOT match "عباسي" if not contains_exact_word(s, t, heh_norm=heh_norm): continue if s not in seen_sentences: seen_sentences.add(s) snippets.append({ "term": t, "sentence": s, "year": row["year"], "title": row["title"], "author": row["author"], "doc_type": row["doc_type"] or "book", "source_name": row["source_name"] or "" }) term_count += 1 if term_count >= per_term_limit: break conn.close() return jsonify({ "status": "ok", "snippets": snippets }) @app.route("/api/author-stats") @app.route("/author-stats") def api_author_stats(): """ Returns the top 10 authors who used the searched word(s) the most. Queries the dedicated author_analytics.db database. """ raw_query = request.args.get("q", "").strip() if not raw_query: return jsonify({"status": "ok", "results": []}) normalize = request.args.get("normalize", "true").lower() in ("true", "1") heh_norm = request.args.get("heh_norm", "true").lower() in ("true", "1") top_n = request.args.get("top_n", 10, type=int) terms = [t.strip().replace("*", "").strip() for t in re.split(r'[,،]+', raw_query) if t.strip()] if not terms: return jsonify({"status": "ok", "results": []}) results = [] for term in terms: stats = author_analytics.get_top_authors_for_term( term=term, top_n=top_n, normalize=normalize, heh_norm=heh_norm ) results.append(stats) return jsonify({"status": "ok", "results": results}) @app.route("/api/check_book_ngram", methods=["POST"]) def api_check_book_ngram(): """Calculates ngrams for a user-supplied book on the fly and compares against DB.""" data = request.get_json() or {} raw_query = data.get("query", "").strip() book_text = data.get("text", "").strip() year = data.get("year", 2024) category = data.get("category", "").strip() or "عام" if not raw_query or not book_text: return jsonify({"status": "error", "message": "متن ۽ ڳولا وارو لفظ ٻئي ضروري آهن."}), 400 clean_text = re.sub(r'\[SECTION:[^\]]+\]', ' ', book_text) user_tokens = sindhi_nlp.tokenize(clean_text, normalize=False) total_user_words = len(user_tokens) if total_user_words == 0: return jsonify({"status": "error", "message": "ڪتاب جي متن مان ڪي به لفظ نه مليا."}), 400 terms = [t.strip().replace("*", "").strip() for t in re.split(r'[,،]+', raw_query) if t.strip()] conn = get_db() cur = conn.cursor() cur.execute("SELECT SUM(total_words) FROM books") db_total_words = cur.fetchone()[0] or 1 results = [] for term in terms: words = term.split() n_size = len(words) if n_size == 0: continue user_ngrams = sindhi_nlp.generate_ngrams(user_tokens, n_size) t_norm = sindhi_nlp.normalize_sindhi(term, strip_diacritics=True, normalize_heh_variants=True) user_count = sum( 1 for ng in user_ngrams if sindhi_nlp.normalize_sindhi(ng, strip_diacritics=True, normalize_heh_variants=True) == t_norm ) user_freq = (user_count / total_user_words * 100.0) if total_user_words > 0 else 0.0 cur.execute("SELECT SUM(count) FROM ngram_counts WHERE ngram_heh_norm = ? AND n_size = ?", (t_norm, n_size)) db_cnt_row = cur.fetchone() db_count = db_cnt_row[0] if db_cnt_row and db_cnt_row[0] is not None else 0 db_freq = (db_count / db_total_words * 100.0) if db_total_words > 0 else 0.0 results.append({ "term": term, "book_count": user_count, "book_freq": user_freq, "db_count": db_count, "db_freq": db_freq }) conn.close() return jsonify({ "status": "ok", "book_total_words": total_user_words, "results": results }) @app.route("/api/submit_book", methods=["POST"]) def api_submit_book(): """Allows public users to submit a book or article for review.""" data = request.get_json() or {} title = data.get("title", "").strip() author = data.get("author", "").strip() authors_list = json.dumps(data.get("authors_list", []), ensure_ascii=False) original_author = data.get("original_author", "").strip() translator = data.get("translator", "").strip() is_translation = 1 if data.get("is_translation") else 0 is_anthology = 1 if data.get("is_anthology") else 0 doc_type = data.get("doc_type", "book").strip() source_name = data.get("source_name", "").strip() year = data.get("year", 2024) category = data.get("category", "").strip() or "عام" full_text = data.get("full_text", "").strip() submitter_name = data.get("submitter_name", "عام واهپيدار").strip() submitter_note = data.get("submitter_note", "").strip() if not title or not full_text: return jsonify({"status": "error", "message": "عنوان ۽ متن لکڻ لازمي آهن."}), 400 conn = get_db() cur = conn.cursor() cur.execute(""" INSERT INTO book_submissions ( title, author, authors_list, original_author, translator, is_translation, is_anthology, doc_type, source_name, year, category, sections_data, submitter_name, submitter_note, status ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending') """, ( title, author, authors_list, original_author, translator, is_translation, is_anthology, doc_type, source_name, year, category, full_text, submitter_name, submitter_note )) conn.commit() conn.close() return jsonify({"status": "ok", "message": "ڪتاب ڪاميابيءَ سان جائزي لاءِ موڪليو ويو."}) # ========================================== # Admin APIs # ========================================== @app.route("/api/admin/check_book") def api_admin_check_book(): """Live search to check if a book title exists.""" title = request.args.get("title", "").strip() if not title: return jsonify({"exists": False}) conn = get_db() cur = conn.cursor() cur.execute("SELECT title, author, year FROM books WHERE TRIM(LOWER(title)) = TRIM(LOWER(?)) LIMIT 1", (title,)) row = cur.fetchone() conn.close() if row: return jsonify({ "exists": True, "book": { "title": row["title"], "author": row["author"], "year": row["year"] } }) return jsonify({"exists": False}) @app.route("/api/admin/add_book", methods=["POST"]) def api_admin_add_book(): """Adds a new publication directly from the Admin Panel and indexes it immediately.""" data = request.get_json() or {} title = data.get("title", "").strip() english_slug = data.get("english_slug", "").strip() author = data.get("author", "").strip() original_author = data.get("original_author", "").strip() translator = data.get("translator", "").strip() is_translation = 1 if data.get("is_translation") else 0 is_anthology = 1 if data.get("is_anthology") else 0 doc_type = data.get("doc_type", "book").strip() source_name = data.get("source_name", "").strip() year = data.get("year") category = data.get("category", "").strip() or "عام" text = data.get("text", "").strip() authors_list = data.get("authors_list", []) if is_translation and not author: author = f"{original_author} (مترجم: {translator})" if translator else original_author if not title or not author or not year or not text: return jsonify({"status": "error", "message": "سمورا خانا ڀرڻ ضروري آهن."}), 400 try: year = int(year) except ValueError: return jsonify({"status": "error", "message": "سال عدد ۾ هجڻ گهرجي."}), 400 os.makedirs("books", exist_ok=True) prefix = doc_type if doc_type != "book" else "book" if english_slug: safe_name = re.sub(r'[^a-zA-Z0-9_-]', '_', english_slug).strip('_') filename = f"{prefix}_{safe_name}_{year}.txt" else: safe_title = re.sub(r'[^\w\s-]', '', title).strip().replace(' ', '_') or "doc" filename = f"{prefix}_{safe_title}_{year}.txt" filepath = os.path.join("books", filename) author_line = f"{original_author} (مترجم: {translator})" if is_translation and translator else author # Write formatted publication file with open(filepath, "w", encoding="utf-8") as f: f.write(f"{year}\n") f.write(f"{title}\n") f.write(f"{author_line}\n") f.write(f"{category}\n") f.write("...............................\n") f.write(text + "\n") conn = sqlite3.connect(DB_FILE, timeout=30.0) conn.row_factory = sqlite3.Row try: conn.execute("PRAGMA journal_mode = WAL;") conn.execute("PRAGMA synchronous = NORMAL;") conn.execute("PRAGMA cache_size = -64000;") conn.execute("PRAGMA temp_store = MEMORY;") except Exception: pass success = process_books_module.process_book(filepath, conn, doc_type=doc_type, source_name=source_name) if success: cur = conn.cursor() cur.execute(""" UPDATE books SET original_author = ?, translator = ?, is_translation = ?, is_anthology = ?, authors_list = ? WHERE filename = ? """, (original_author, translator, is_translation, is_anthology, json.dumps(authors_list, ensure_ascii=False), filename)) # If this entry was published from a submission review, mark submission approved sub_id = data.get("submission_id") if sub_id: cur.execute("UPDATE book_submissions SET status = 'approved' WHERE id = ?", (sub_id,)) conn.commit() # Register multi-word authors as compound person entities if is_translation: if original_author and len(original_author.split()) > 1: process_books_module.register_compound_person(original_author, role="اصل ليکڪ", conn=conn) if translator and len(translator.split()) > 1: process_books_module.register_compound_person(translator, role="مترجم", conn=conn) else: for a_name in (authors_list if authors_list else [author]): clean_a = a_name.strip() if clean_a and len(clean_a.split()) > 1: process_books_module.register_compound_person(clean_a, role="ليکڪ", conn=conn) cur.execute("SELECT total_words FROM books WHERE filename = ?", (filename,)) row = cur.fetchone() words_count = row[0] if row else 0 conn.close() # Instant cache update in memory so the new book shows immediately try: refresh_year_totals_cache() except Exception: pass return jsonify({ "status": "ok", "title": title, "filename": filename, "words_count": words_count, "ngrams_added": CACHED_DISTINCT_NGRAMS }) else: conn.close() return jsonify({"status": "error", "message": "مواد کي پروسيس ڪرڻ ۾ رڪاوٽ آئي."}), 500 @app.route("/api/admin/books", methods=["GET", "DELETE"]) def api_admin_books(): """Returns list of all published books/articles or deletes a publication.""" conn = get_db() cur = conn.cursor() if request.method == "DELETE": book_id = request.args.get("id", type=int) if not book_id: conn.close() return jsonify({"status": "error", "message": "آئي ڊي گهربل آهي."}), 400 cur.execute("SELECT filename, title FROM books WHERE id = ?", (book_id,)) row = cur.fetchone() if not row: conn.close() return jsonify({"status": "error", "message": "ڪتاب نه مليو."}), 404 filename = row["filename"] title = row["title"] cur.execute("DELETE FROM concordance WHERE book_id = ?", (book_id,)) cur.execute("DELETE FROM book_sections WHERE book_id = ?", (book_id,)) cur.execute("DELETE FROM books WHERE id = ?", (book_id,)) conn.commit() conn.close() if filename: try: author_analytics.remove_book(filename) except Exception: pass fp = os.path.join("books", filename) if os.path.exists(fp): try: os.remove(fp) except Exception: pass return jsonify({"status": "ok", "message": f"'{title}' ڪاميابيءَ سان ڊليٽ ڪيو ويو."}) # GET method with fast pagination q = request.args.get("q", "").strip() doc_type = request.args.get("doc_type", "").strip() page = request.args.get("page", default=1, type=int) limit = request.args.get("limit", default=50, type=int) offset = max(0, (page - 1) * limit) where_clauses = ["1=1"] params = [] if q: where_clauses.append("(title LIKE ? OR author LIKE ?)") params.extend([f"%{q}%", f"%{q}%"]) if doc_type and doc_type != "all": where_clauses.append("doc_type = ?") params.append(doc_type) where_str = " AND ".join(where_clauses) cur.execute(f"SELECT COUNT(*) FROM books WHERE {where_str}", params) total_count = cur.fetchone()[0] sql = f""" SELECT id, filename, title, author, original_author, translator, is_translation, is_anthology, doc_type, source_name, year, category, total_words, created_at FROM books WHERE {where_str} ORDER BY id DESC LIMIT ? OFFSET ? """ fetch_params = list(params) + [limit, offset] cur.execute(sql, fetch_params) books = [dict(r) for r in cur.fetchall()] conn.close() return jsonify({ "status": "ok", "books": books, "total_count": total_count, "page": page, "limit": limit, "total_pages": (total_count + limit - 1) // limit if limit > 0 else 1 }) @app.route("/api/admin/book/<int:book_id>") def api_admin_get_book(book_id): """Fetches full book details including text and sections for editing.""" conn = get_db() cur = conn.cursor() cur.execute("SELECT * FROM books WHERE id = ?", (book_id,)) row = cur.fetchone() if not row: conn.close() return jsonify({"status": "error", "message": "ڪتاب نه مليو."}), 404 book = dict(row) cur.execute("SELECT section_type, section_title, section_author, word_count FROM book_sections WHERE book_id = ? ORDER BY id ASC", (book_id,)) book["sections"] = [dict(s) for s in cur.fetchall()] conn.close() text_content = "" parsed_sections = [] if book.get("filename"): fp = os.path.join("books", book["filename"]) if os.path.exists(fp): parsed = sindhi_nlp.parse_book_file(fp) if parsed: text_content = parsed.get("text", "") parsed_sections = parsed.get("sections", []) book["text"] = text_content book["parsed_sections"] = parsed_sections return jsonify({"status": "ok", "book": book}) @app.route("/api/admin/update_book", methods=["POST"]) def api_admin_update_book(): """Updates an existing publication directly from the Admin Panel and re-indexes it.""" data = request.get_json() or {} book_id = data.get("id") if not book_id: return jsonify({"status": "error", "message": "ڪتاب جي آئي ڊي ضروري آهي."}), 400 conn = get_db() cur = conn.cursor() cur.execute("SELECT * FROM books WHERE id = ?", (book_id,)) old_book = cur.fetchone() if not old_book: conn.close() return jsonify({"status": "error", "message": "ڪتاب رڪارڊ نه مليو."}), 404 old_book = dict(old_book) title = data.get("title", "").strip() author = data.get("author", "").strip() original_author = data.get("original_author", "").strip() translator = data.get("translator", "").strip() is_translation = 1 if data.get("is_translation") else 0 is_anthology = 1 if data.get("is_anthology") else 0 doc_type = data.get("doc_type", "book").strip() source_name = data.get("source_name", "").strip() year = data.get("year") category = data.get("category", "").strip() or "عام" text = data.get("text", "").strip() authors_list = data.get("authors_list", []) if is_translation and not author: author = f"{original_author} (مترجم: {translator})" if translator else original_author if not title or not author or not year or not text: conn.close() return jsonify({"status": "error", "message": "سمورا خانا ڀرڻ ضروري آهن."}), 400 try: year = int(year) except ValueError: conn.close() return jsonify({"status": "error", "message": "سال عدد ۾ هجڻ گهرجي."}), 400 old_filename = old_book["filename"] filepath = os.path.join("books", old_filename) if old_filename else "" if not filepath or not os.path.exists(filepath): safe_title = re.sub(r'[^\w\s-]', '', title).strip().replace(' ', '_') or "doc" filepath = os.path.join("books", f"{doc_type}_{safe_title}_{year}.txt") old_filename = os.path.basename(filepath) author_line = f"{original_author} (مترجم: {translator})" if is_translation and translator else author with open(filepath, "w", encoding="utf-8") as f: f.write(f"{year}\n") f.write(f"{title}\n") f.write(f"{author_line}\n") f.write(f"{category}\n") f.write("...............................\n") f.write(text + "\n") cur.execute("DELETE FROM concordance WHERE book_id = ?", (book_id,)) cur.execute("DELETE FROM book_sections WHERE book_id = ?", (book_id,)) conn.commit() conn.close() conn_proc = sqlite3.connect(DB_FILE, timeout=30.0) conn_proc.row_factory = sqlite3.Row try: conn_proc.execute("PRAGMA journal_mode = WAL;") conn_proc.execute("PRAGMA synchronous = NORMAL;") conn_proc.execute("PRAGMA cache_size = -64000;") conn_proc.execute("PRAGMA temp_store = MEMORY;") except Exception: pass success = process_books_module.process_book(filepath, conn_proc, doc_type=doc_type, source_name=source_name) if success: cur_proc = conn_proc.cursor() cur_proc.execute(""" UPDATE books SET original_author = ?, translator = ?, is_translation = ?, is_anthology = ?, authors_list = ? WHERE id = ? """, (original_author, translator, is_translation, is_anthology, json.dumps(authors_list, ensure_ascii=False), book_id)) conn_proc.commit() if is_translation: if original_author and len(original_author.split()) > 1: process_books_module.register_compound_person(original_author, role="اصل ليکڪ", conn=conn_proc) if translator and len(translator.split()) > 1: process_books_module.register_compound_person(translator, role="مترجم", conn=conn_proc) else: for a_name in (authors_list if authors_list else [author]): clean_a = a_name.strip() if clean_a and len(clean_a.split()) > 1: process_books_module.register_compound_person(clean_a, role="ليکڪ", conn=conn_proc) cur_proc.execute("SELECT total_words FROM books WHERE id = ?", (book_id,)) row = cur_proc.fetchone() words_count = row[0] if row else 0 conn_proc.close() try: refresh_year_totals_cache() except Exception: pass return jsonify({ "status": "ok", "title": title, "words_count": words_count, "message": f"'{title}' ڪاميابيءَ سان اپڊيٽ ۽ پروسيس ڪيو ويو." }) else: conn_proc.close() return jsonify({"status": "error", "message": "مواد اپڊيٽ ڪرڻ ۾ رڪاوٽ آئي."}), 500 @app.route("/api/admin/submissions", methods=["GET", "DELETE"]) def api_admin_submissions(): """Fetches list of external submissions or deletes a submission.""" conn = get_db() cur = conn.cursor() if request.method == "DELETE": sub_id = request.args.get("id", type=int) if not sub_id: conn.close() return jsonify({"status": "error", "message": "آئي ڊي ضروري آهي."}), 400 cur.execute("DELETE FROM book_submissions WHERE id = ?", (sub_id,)) conn.commit() conn.close() return jsonify({"status": "ok", "message": "خارجي مواد ڪاميابيءَ سان ڊليٽ ڪيو ويو."}) cur.execute(""" SELECT id, title, author, original_author, translator, is_translation, doc_type, source_name, year, category, submitter_name, submitter_note, status, created_at, sections_data FROM book_submissions ORDER BY id DESC """) submissions = [dict(r) for r in cur.fetchall()] conn.close() return jsonify({"status": "ok", "submissions": submissions}) @app.route("/api/admin/submission/<int:sub_id>") def api_admin_get_submission(sub_id): """Fetches submission data for viewing and editing.""" conn = get_db() cur = conn.cursor() cur.execute("SELECT * FROM book_submissions WHERE id = ?", (sub_id,)) row = cur.fetchone() conn.close() if not row: return jsonify({"status": "error", "message": "رڪارڊ نه مليو."}), 404 return jsonify({"status": "ok", "submission": dict(row)}) @app.route("/api/admin/reject_submission", methods=["POST"]) def api_admin_reject_submission(): """Rejects and deletes a submission.""" data = request.get_json() or {} sub_id = data.get("id") if not sub_id: return jsonify({"status": "error", "message": "آئي ڊي ضروري آهي."}), 400 conn = get_db() cur = conn.cursor() cur.execute("DELETE FROM book_submissions WHERE id = ?", (sub_id,)) conn.commit() conn.close() return jsonify({"status": "ok", "message": "خارجي مواد رد ۽ ڊليٽ ڪيو ويو."}) @app.route("/api/admin/authors") def api_admin_authors(): """Returns list of unique author names for datalists.""" conn = get_db() cur = conn.cursor() names = set() cur.execute("SELECT author, original_author, translator, authors_list FROM books") for r in cur.fetchall(): for val in [r[0], r[1], r[2]]: if val: c = re.sub(r'\(.*?\)', '', val).strip() if c: for part in re.split(r'[,،]+', c): p = part.strip() if p: names.add(p) if r[3]: try: al = json.loads(r[3]) for p in al: if p and p.strip(): names.add(p.strip()) except Exception: pass conn.close() sorted_authors = sorted(list(names)) return jsonify({"status": "ok", "authors": sorted_authors}) @app.route("/api/admin/writers") def api_admin_writers(): """Returns writers/authors of books and articles with publications count and total words.""" conn = get_db() cur = conn.cursor() cur.execute(""" SELECT author, doc_type, COUNT(*) as pub_count, SUM(total_words) as total_words, MIN(year) as min_year, MAX(year) as max_year, GROUP_CONCAT(title, ' • ') as titles FROM books WHERE author IS NOT NULL AND TRIM(author) != '' GROUP BY author, doc_type ORDER BY pub_count DESC, total_words DESC """) writers = [dict(r) for r in cur.fetchall()] conn.close() return jsonify({"status": "ok", "writers": writers}) @app.route("/api/famous_personalities") def api_famous_personalities(): """Returns top famous personalities by year with contextual disambiguation.""" fp_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "yearly_famous_personalities.json") if os.path.exists(fp_path): try: with open(fp_path, "r", encoding="utf-8") as f: data = json.load(f) return jsonify(data) except Exception as e: return jsonify({"status": "error", "message": str(e)}), 500 return jsonify({"status": "error", "message": "File not found"}), 404 @app.route("/api/trends-entities") @app.route("/api/trends_entities") def api_trends_entities(): """Returns top famous personalities & cities with ranks, movements, and full search indexing.""" te_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "yearly_trends_entities.json") if os.path.exists(te_path): try: with open(te_path, "r", encoding="utf-8") as f: data = json.load(f) return jsonify(data) except Exception as e: return jsonify({"status": "error", "message": str(e)}), 500 return jsonify({"status": "error", "message": "Trends entities file not found"}), 404 if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) print(f"Starting Sindhi Books Ngram Viewer at http://localhost:{port}") app.run(host="0.0.0.0", port=port, debug=False)
"""
3_web_app.py
Sindhi Books Ngram Viewer (سنڌي ڪتابن جي اين گرام)
Complete Web System with:
- Main Search & Ngram Chart (Google Ngram Viewer style)
- Corpus Selection: Books (ڪتاب), Newspaper Articles (اخبارن جا مضمون), Pamphlets (پمفليٽ), or Both/Combined (گڏيل)
- Multi-word Concordance Filtering (word-by-word filter pills)
- Section Attributions (e.g. مھاڳ: نذار قباني)
- Public Book Checker & Live Ngram Comparison (/check-book)
- Public Book & Article Submission for Admin Review
- Admin Publication Ingestion with Multi-box Sections & Document Types
- Author Chips / Tag Input (press comma or enter)
- Submissions Review & Approval Pipeline
- Database Reset for Fresh Start
"""
import os
import sys
import re
import json
import sqlite3
import hashlib
import html
from typing import Dict, List, Any
from datetime import datetime
import collections
from flask import Flask, request, jsonify, render_template_string, send_from_directory, redirect
# Ensure UTF-8 stdout encoding for Windows
if sys.platform == 'win32':
try:
sys.stdout.reconfigure(encoding='utf-8')
except Exception:
pass
import sindhi_nlp
import importlib
process_books_module = importlib.import_module("1_process_books")
import author_analytics
from templates import (
COMMON_CSS,
MAIN_PAGE_TEMPLATE,
ABOUT_PAGE_TEMPLATE,
TOP50_PAGE_TEMPLATE,
USAGE_PAGE_TEMPLATE
)
# Hardcoded max cutoff date: September 30, 2026
HARDCODED_CUTOFF_DATE = "2026-09-30"
LAST_UPDATE_EN = "September 30, 2026"
LAST_UPDATE_SD = "30 سيپٽمبر 2026ع"
MAX_ALLOWED_YEAR = 2026
def resolve_database():
local_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ngram_database.db")
if os.path.exists(local_path):
return local_path
try:
from huggingface_hub import hf_hub_download
token = os.environ.get("HF_TOKEN")
print("Fetching ngram_database.db from dataset repo...")
return hf_hub_download(
repo_id="hellosindh/sindhi-ngram-database",
filename="ngram_database.db",
repo_type="dataset",
token=token,
)
except Exception as e:
print(f"Error fetching DB from Hub: {e}")
return local_path
DB_FILE = resolve_database()
app = Flask(__name__)
# Enable CORS for all API routes so external frontends (hellosindh.com) can call directly
@app.after_request
def add_cors_headers(response):
response.headers["Access-Control-Allow-Origin"] = "*"
response.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS, HEAD"
response.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization, X-Requested-With"
return response
@app.route('/api/<path:path>', methods=['OPTIONS'])
def options_handler(path):
return ('', 204)
# Ensure DB schema on startup
try:
_conn = process_books_module.init_database(DB_FILE)
_conn.close()
except Exception as e:
print(f"DB Init warning: {e}")
def get_db():
conn = sqlite3.connect(DB_FILE)