thumbnail , ...

This commit is contained in:
hsafaei
2025-12-17 11:43:22 +03:30
parent f4e8832e61
commit 525b429d6a
4 changed files with 198 additions and 74 deletions
+86 -16
View File
@@ -32,6 +32,13 @@ load_dotenv(dotenv_path="config.env")
host = os.getenv("HOST_160")
password = os.getenv("HOST_160_PASS")
# host = os.getenv("HOST_112")
# password = os.getenv("HOST_112_PASS")
# host = os.getenv("HOST_H102")
# password = os.getenv("HOST_H102_PASS")
# print( "---------------->>>>>>>>>>>>>>>", host )
# host=os.getenv('HOST_113')
@@ -43,6 +50,7 @@ print(".... majles_codes_update_steps ......", host)
path_base_map = "G:/Project2/gateway_php/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
# -------------------------------------
# ----- یک بار فقط
# ----- پشتیبان گیری از داده های جدید داتیک
@@ -105,6 +113,19 @@ file_path = "G:/Project2/160_dotic/mj_rg_section_doctic_14040824.zip"
# elastic.createIndex( 'mj_rg_section', 'majles', 'mj_rg_section', path_base_map+ 'majles/'+'mj_qa_section_new.json')
# restore_correct_date_to_elastic(elastic, file_path, "mj_rg_section", "G:/Project2/160_dotic/date_log_error_rgsection.txt" )
# -------------------------------------
# ----- mj_mashruh
file_path = "G:/Project2/160_dotic/mj_mashruh.zip"
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_mashruh", "mj_mashruh")
elastic.createIndex( 'mj_mashruh', 'majles', 'mj_mashruh', path_base_map+ 'majles/'+'mj_mashruh.json' )
restore_correct_date_to_elastic(elastic, file_path, "mj_mashruh", "G:/Project2/160_dotic/date_log_error_mashruh.txt" )
# --------------------------------------------- 1 ------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------------------
# --- مواردی از قانونهای جدید که فیلد زیر را ندارند باید اصلاح شوند
@@ -163,11 +184,15 @@ file_path = "G:/Project2/160_dotic/mj_rg_section_doctic_14040824.zip"
# ctx._source.main_type = 'قانون';
# ctx._source.main_type_key = 'qasection';
# """,
# "lang": "painless",
# },
# "lang": "painless"
# }
# }
# elastic.updateByQueryIndex("mj_df_qanon", body)
#elastic.backupIndexToZipfile("G:/Project2/160_dotic/majles_14040918", "mj_df_qanon", "mj_df_qanon_1_date")
# --------------------------------------------- 3 ------------------------------------------------------------------
# --- درج داده های جدید مقررات و آراء در فهرست همه
# ---------------------------------------------------------------------------------------------------------------
@@ -210,12 +235,12 @@ file_tasmim = "G:/Project2/160_dotic/duplicate_tasmim.json"
# elastic.restorFileToElastic2('G:/Project2/160_dotic/mj_qa_qanon_3_base_dotic.zip', 'mj_qa_qanon', 'majles', False, 'mj_qa_qanon')
# # #------------------------------------------
duplicate_list = {}
file_excel = r"G:\Project2\dataParsers\data\qavanin_files\qavanin_output4.xlsx"
import_excel_before_to_elastic(elastic, file_excel, "mj_qa_qanon", duplicate_list)
# duplicate_list = {}
# file_excel = r"G:\Project2\dataParsers\data\qavanin_files\qavanin_output4.xlsx"
# import_excel_before_to_elastic(elastic, file_excel, "mj_qa_qanon", duplicate_list)
with open(file_before, 'w', encoding='utf8') as f :
json.dump(duplicate_list, f, ensure_ascii=False, indent=4)
# with open(file_before, 'w', encoding='utf8') as f :
# json.dump(duplicate_list, f, ensure_ascii=False, indent=4)
# # # #------------------------------------------
@@ -229,7 +254,7 @@ with open(file_before, 'w', encoding='utf8') as f :
# json.dump(duplicate_list, f, ensure_ascii=False, indent=4)
# # # #------------------------------------------
# # # # #------------------------------------------
# duplicate_list = {}
# with open(file_after, 'r', encoding='utf8') as f :
# duplicate_list = json.loads( f.read())
@@ -243,6 +268,14 @@ with open(file_before, 'w', encoding='utf8') as f :
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_qanon", "mj_qa_qanon_4_base_excel")
#---------تنظیم شد mj_qa_qanon_new.json
# #----------------------------
# PUT mj_qa_qanon/_settings
# {
# "index" : {
# "max_result_window" : 200000
# }
# }
# .....
@@ -251,18 +284,55 @@ with open(file_before, 'w', encoding='utf8') as f :
# -- اصلاح ساختار اسکیما نماش و تغییرات برای ساختار تاریخ تغییر یافته و تست و بررسی
# .....
# .....
# ------------------------------------
# ------------------------------------
# ------------------------------------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------------
#------------------------------------
#--- mj_qa_section
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_section", "mj_qa_section_1_base")
# بررسی پر بودن main_type مجلس برای نوع اصلی/تبعی/مهذب # و تغییر به mom_type
#### schema changed --> qasection_mom_type
# # # POST mj_qa_section/_update_by_query
# body = {
# "query": {"terms": {"main_type": ["اصلی", "تبعی"]}},
# "script": {
# "source": """
# ctx._source.mom_type = ctx._source.main_type;
# ctx._source.main_type = 'قانون'
# """,
# "lang": "painless",
# },
# }
# elastic.updateByQueryIndex("mj_qa_section", body)
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_mashruh", "mj_mashruh")
# elastic.createIndex( 'mj_mashruh', 'majles', 'mj_mashruh', path_base_map+ 'majles/'+'mj_mashruh.json' )
# elastic.restorFileToElastic2('G:/Project2/160_dotic/mj_mashruh.zip', 'mj_mashruh', 'majles', False, 'mj_mashruh')
#--- mj_qa_section ???
# بررسی پر بودن main_type مجلس برای نوع اصلی/تبعی/مهذب
# و تغییر به mom_type
# schema ???
# 'key' => 'mom_type',
# 'label' => 'نوع اصلی/تبعی/مهذب',
# elastic.createIndex( 'mj_qa_qanon', 'majles', 'mj_qa_qanon')
# elastic.restorFileToElastic2('G:/Project2/160_dotic/mj_qa_qanon_base_excel.zip', 'mj_qa_qanon', 'majles', False, 'mj_qa_qanon')
# elastic.createIndex( 'mj_qa_qanon', 'majles', 'mj_qa_qanon', path_base_map+ 'majles/'+'mj_qa_qanon_new.json' )
# elastic.restorFileToElastic2('G:/Project2/160_dotic/majles_14040918/mj_qa_qanon_4_base_excel.zip', 'mj_qa_qanon', 'majles', False, 'mj_qa_qanon')
# elastic.createIndex( 'mj_df_qanon', 'majles', 'mj_df_qanon', path_base_map+ 'majles/'+'mj_df_qanon_new.json' )
# elastic.restorFileToElastic2('G:/Project2/160_dotic/majles_14040918/mj_df_qanon_1_date.zip', 'mj_df_qanon', 'majles', False, 'mj_df_qanon')
# elastic.backupIndexToZipfile("G:/Project2/160_dotic", "mj_qa_semantic_section", "mj_qa_semantic_section")
+66 -57
View File
@@ -4,15 +4,14 @@ from PIL import Image, ImageDraw, ImageFont
import numpy as np
import random
from typing import Union, List
from PIL import Image, ImageDraw, ImageFont
import math
print(fitz.version) # مثلاً ('1.24.4', '...', ...)
# ---------- تنظیمات شما ----------
INPUT_DIR = Path(r"D:\init_mahdi\project\watermark_source\in_test")
# INPUT_DIR = Path(r"D:\init_mahdi\project\watermark_source\in_test\4712")
OUTPUT_DIR = Path(r"D:\init_mahdi\project\watermark_source\o_test")
INPUT_DIR = Path(r"E:\pdf advar")
OUTPUT_DIR = Path(r".\data\qavanin_files\advar_thumb1")
WATERMARK_TEXT = [
" معاونت قوانین مجلس شورای اسلامی",
"اداره کل اسناد و اطلاع رسانی قوانین",
@@ -22,7 +21,7 @@ WATERMARK2_TEXT = "قانون‌یار"
DPI = 150
MAX_SIZE = 300
# ----------------------------------
FONT_PATH = r"Iranian Sans.ttf"
FONT_PATH = r".\app\parvande_qanon\Iranian Sans.ttf"
SUPPORTED_IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tiff", ".tif"}
SUPPORTED_PDF_EXTS = {".pdf"}
@@ -31,16 +30,17 @@ import random
from pathlib import Path
from typing import Union, List, Tuple
from PIL import Image, ImageDraw, ImageFont
import arabic_reshaper
from bidi.algorithm import get_display
def add_watermark(
img: Image.Image,
primary_text: Union[str, List[str]],
primary_text: Union[List[str]],
sec_text: str,
font_path: str = FONT_PATH,
primary_opacity: int = 50,
secondary_opacity: int = 15,
grid_rows: int = 10, # ✅ تعداد سطرهای شبکه
primary_opacity: int = 70,
secondary_opacity: int = 70,
grid_rows: int = 4, # ✅ تعداد سطرهای شبکه
grid_cols: int = 1, # ✅ تعداد ستون‌های شبکه
rotation_range: Tuple[int, int] = (-15, 13),
font_size_primary: int = 16,
@@ -93,6 +93,8 @@ def add_watermark(
draw_obj.text((x, y), text, font=font, fill=fill)
# ===== 1. واترمارک ثانویه: فقط 4 گوشه =====
sec_text = get_display(arabic_reshaper.reshape(sec_text))
if sec_text.strip():
bbox = draw.textbbox((0, 0), sec_text, font=font_s)
tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1]
@@ -109,18 +111,23 @@ def add_watermark(
(x, y),
sec_text,
font_s,
fill_color=(255, 255, 255),
fill_color=(236, 236, 238),
stroke_color=(0, 0, 0),
opacity=secondary_opacity,
stroke_width=1,
)
# ===== 2. واترمارک اصلی: شبکه‌بندی + رندوم درون هر سلول =====
primary_texts = (
[primary_text]
if isinstance(primary_text, str)
else [t for t in primary_text if t.strip()]
)
# # ===== 2. واترمارک اصلی: شبکه‌بندی + رندوم درون هر سلول =====
# primary_texts = (
# [primary_text]
# if isinstance(primary_text, str)
# else [t for t in primary_text if t.strip()]
# )
primary_texts = []
for text in primary_text :
primary_texts.append(get_display(arabic_reshaper.reshape(text)))
if not primary_texts:
return img.convert("RGB")
@@ -149,55 +156,57 @@ def add_watermark(
x1 = x0 + cell_width
y1 = y0 + cell_height
# for text in primary_texts :
text = random.choice(primary_texts).strip()
if not text:
continue
offset = 0
if text:
# ابعاد دقیق متن
bbox = draw.textbbox((0, 0), text, font=font_p)
tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1]
# ابعاد دقیق متن
bbox = draw.textbbox((0, 0), text, font=font_p)
tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1]
# ✅ موقعیت پایه: یک نقطه داخل سلول، نه الزاماً مرکز
# مثلاً 20%~80% عرض سلول و 30%~70% ارتفاع سلول
base_x = x0 + random.uniform(0.2, 0.8) * cell_width
base_y = y0 + offset + random.uniform(0.3, 0.7) * cell_height
# ✅ موقعیت پایه: یک نقطه داخل سلول، نه الزاماً مرکز
# مثلاً 20%~80% عرض سلول و 30%~70% ارتفاع سلول
base_x = x0 + random.uniform(0.2, 0.8) * cell_width
base_y = y0 + random.uniform(0.3, 0.7) * cell_height
# ✅ انحراف تصادفی در محدوده منطقی (نه بسته به safe_w که گاهی صفر می‌شد)
dx = random.uniform(-offset_limit_x, offset_limit_x)
dy = random.uniform(-offset_limit_y, offset_limit_y)
final_x = max(0, min(width - 1, base_x + dx))
final_y = max(0, min(height - 1, base_y + dy))
# ✅ انحراف تصادفی در محدوده منطقی (نه بسته به safe_w که گاهی صفر می‌شد)
dx = random.uniform(-offset_limit_x, offset_limit_x)
dy = random.uniform(-offset_limit_y, offset_limit_y)
final_x = max(0, min(width - 1, base_x + dx))
final_y = max(0, min(height - 1, base_y + dy))
# ✅ زاویه تصادفی
angle = random.randint(*rotation_range)
# ✅ زاویه تصادفی
angle = random.randint(*rotation_range)
# ساخت لایه متن
pad = 20 # padding around text for rotation
layer_w, layer_h = int(tw + 2 * pad), int(th + 2 * pad)
txt_layer = Image.new("RGBA", (layer_w, layer_h), (0, 0, 0, 0))
d = ImageDraw.Draw(txt_layer)
# ساخت لایه متن
pad = 20 # padding around text for rotation
layer_w, layer_h = int(tw + 2 * pad), int(th + 2 * pad)
txt_layer = Image.new("RGBA", (layer_w, layer_h), (0, 0, 0, 0))
d = ImageDraw.Draw(txt_layer)
draw_text_with_stroke(
d,
(pad, pad), # متن از گوشه شروع می‌شود — ساده‌تر و دقیق‌تر
text,
font_p,
fill_color=(130, 130, 135),
stroke_color=(0, 0, 0),
opacity=primary_opacity,
stroke_width=1,
)
draw_text_with_stroke(
d,
(pad, pad), # متن از گوشه شروع می‌شود — ساده‌تر و دقیق‌تر
text,
font_p,
fill_color=(255, 255, 255),
stroke_color=(0, 0, 0),
opacity=primary_opacity,
stroke_width=1,
)
rotated = txt_layer.rotate(angle, expand=True, resample=Image.BICUBIC)
rw, rh = rotated.size
rotated = txt_layer.rotate(angle, expand=True, resample=Image.BICUBIC)
rw, rh = rotated.size
# موقعیت نهایی: مرکز لایه چرخیده روی (final_x, final_y)
pos_x = int(final_x - rw / 2)
pos_y = int(final_y - rh / 2)
pos_x = max(0, min(pos_x, width - rw))
pos_y = max(0, min(pos_y, height - rh))
# موقعیت نهایی: مرکز لایه چرخیده روی (final_x, final_y)
pos_x = int(final_x - rw / 2)
pos_y = int(final_y - rh / 2)
pos_x = max(0, min(pos_x, width - rw))
pos_y = max(0, min(pos_y, height - rh))
img.alpha_composite(rotated, (pos_x, pos_y))
img.alpha_composite(rotated, (pos_x, pos_y))
# offset += 20
return img.convert("RGB")
@@ -40,9 +40,21 @@ def correct_qanon_date_json(data, error_list):
data_new = []
for item in data:
id = item["_id"]
# یکبار فقط نیاز بود
id = str(id).replace('mj_mashruh_', 'mh')
item["_id"] = id
item["_source"]["id"] = id
item["_source"] = repair_object_persian_date(
item["_source"], "ts_date", error_list, id, ""
)
#--> mj_mashruh
if "meet_date" in item["_source"]:
item["_source"] = repair_object_persian_date(
item["_source"], "meet_date", error_list, id, ""
)
if "exec_date" in item["_source"]:
item["_source"] = repair_object_persian_date(
item["_source"], "exec_date", error_list, id, ""
@@ -88,6 +100,34 @@ def correct_qanon_date_json(data, error_list):
data_new.append(item)
return data_new
def normal_data_json(data):
data_new = []
for item in data:
id = item["_id"]
if 'content' in item["_source"] :
item["_source"]['content'] = text_normal.normalize_qanon(item["_source"]['content'])
if 'majles_name' in item["_source"] :
item["_source"]['majles_name'] = text_normal.normalize_qanon(item["_source"]['majles_name'])
if 'title' in item["_source"] :
item["_source"]['title'] = text_normal.normalize_qanon(item["_source"]['title'])
if "talker" in item["_source"]:
talker = item["_source"]["talker"]
if 'organ' in talker :
talker['organ'] = text_normal.normalize_qanon(talker['organ'])
if 'semat' in talker :
talker['semat'] = text_normal.normalize_qanon(talker['semat'])
if 'name' in talker :
talker['name'] = text_normal.normalize_qanon(talker['name'])
item["_source"]["talker"]=talker
data_new.append(item)
return data_new
# اصلاح تاریخ فارسی به ذخیره سازی استاندارد date
def restore_correct_date_to_elastic(elastic, file_path, index_name, file_error=''):
@@ -107,6 +147,8 @@ def restore_correct_date_to_elastic(elastic, file_path, index_name, file_error='
data = json.loads(file.read())
data_new = correct_qanon_date_json(data, error_list)
if index_name == 'mj_mashruh' :
data_new = normal_data_json(data_new)
elastic.importJsonDataToElastic(data_new, index_name, [], True)
counter += len(data)
# print('-'*10, 'len()', str(counter) + '/ ' + str(len(data)) + ' , ' +str(len(data_new)) )