This commit is contained in:
init_mahdi
2026-11-28 16:36:19 +00:00
parent f7f9e85b02
commit 31a0647f77
111 changed files with 23944 additions and 3 deletions
+219
View File
@@ -0,0 +1,219 @@
from pydantic import BaseModel
import time
import os
import json
import orjson
from pathlib import Path
from typing import List, Dict, Optional
def load_orjson(path: str | Path):
path = Path(path)
with path.open("rb") as f: # باید باینری باز بشه برای orjson
return orjson.loads(f.read())
def save_orjson(path, data):
with open(path, "wb") as f:
f.write(
orjson.dumps(data, option=orjson.OPT_INDENT_2 | orjson.OPT_NON_STR_KEYS)
)
system_prompt = """# Role
You are an advanced Persian NLP information extraction engine specialized in semantic keyword extraction, entity recognition, and legal document analysis.
# Task
You will receive a text divided into multiple segments. Each segment has:
- `title`: The title or heading of the document.
- `id`: A unique identifier for a text segment.
- `content`: The text of that segment.
Your task is to extract meaningful keywords and concepts from the entire input and classify them into exactly three categories.
## 1. Named Entities (اشخاص، مکان‌ها، زمان‌ها و موجودیت‌ها)
Extract explicitly mentioned entities, including:
- Persons and individuals
- Organizations, institutions, companies, and governmental bodies
- Geographical locations, cities, countries, and regions
- Dates, years, time periods, and historical events
- Laws, regulations, documents, and official instruments when referenced as identifiable entities
- Other specifically named entities
## 2. Legal Constraints and Provisions (قیود، احکام و الزامات)
Extract concepts that express legal, regulatory, or normative constraints, including:
- Obligations and duties (الزام، مکلف بودن، موظف بودن)
- Prohibitions and restrictions (ممنوعیت، عدم جواز)
- Permissions and authorizations (اجازه، مجاز بودن)
- Conditions and prerequisites (مشروط بودن، منوط بودن)
- Exceptions and exemptions (استثنا، معافیت)
- Deadlines and time limits
- Penalties, sanctions, and legal consequences
- Rights, entitlements, and responsibilities
- Quantitative and qualitative limitations
Extract the meaningful legal concept, not merely isolated grammatical words.
## 3. Topics and Predicates (موضوعات و محمول‌ها)
Extract the main subjects, concepts, and semantic predicates discussed in the text, including:
- Main topics and subtopics
- Legal, administrative, economic, social, and technical concepts
- Actions, processes, and operations
- States, properties, and characteristics
- Relationships between concepts
- Subject-predicate semantic expressions
Prefer concise, meaningful noun phrases or semantic expressions rather than generic individual words.
# ID Mapping Requirements
For every extracted keyword or concept:
- Provide all segment IDs in which it is explicitly mentioned or semantically expressed.
- A keyword must not be associated with an ID unless there is actual textual evidence in that segment.
- If the same entity or concept appears in multiple segments, merge it into a single entry and collect all corresponding IDs.
- Normalize equivalent expressions when they clearly refer to the same entity or concept.
- Preserve distinctions between concepts that are related but not semantically identical.
- Do not infer references or associations that are not supported by the input.
- Do not assign an ID based solely on the document title unless the title itself contains the extracted keyword.
# Extraction Rules
1. Extract informative and discriminative keywords; avoid generic words, filler words, and meaningless expressions.
2. Preserve important modifiers when they change the meaning of a concept.
3. Do not extract stopwords, auxiliary verbs, or grammatical particles independently.
4. Do not generate synonyms or concepts that are absent from the input.
5. Avoid redundant entries across the same category.
6. A concept may legitimately appear in more than one category if it plays different semantic roles. However, avoid unnecessary duplication.
7. Preserve the original Persian terminology whenever possible.
8. Do not summarize or rewrite the source text.
9. Do not fabricate entities, legal provisions, dates, or relationships.
10. Prefer high precision over high recall: extracting fewer accurate keywords is better than generating irrelevant ones.
# STRICT LANGUAGE & LITERAL PRESERVATION POLICY (CRITICAL)
These rules are mandatory and have the highest priority during keyword extraction.
1. The input text is the ONLY authoritative source for the language and wording of extracted keywords.
2. If the source text is Persian, ALL extracted keyword values MUST be written in Persian.
3. NEVER translate Persian keywords, entities, legal concepts, topics, actions, or predicates into English.
4. NEVER translate English keywords into Persian if they appear explicitly in the source text. Preserve the original language of the source expression.
5. Preserve the exact original wording of every extracted keyword as it appears in the source text.
- Do not translate.
- Do not paraphrase.
- Do not rewrite.
- Do not replace words with synonyms.
- Do not generate English equivalents.
- Do not linguistically normalize or simplify expressions.
6. Do not introduce any word, phrase, explanation, or interpretation that does not explicitly exist in the source text.
7. The `keyword` field must contain only the extracted expression itself, without explanations, translations, English descriptions, or additional commentary.
8. Do not use English descriptions or explanations inside keyword values, even when the extracted concept has a well-known English equivalent.
9. The `type` fields MUST use the exact predefined English enum values specified in the output schema. This is the ONLY permitted use of English in the output, apart from structural JSON keys and IDs.
10. Before generating the final JSON, verify every `keyword` against the original input segments:
- Confirm that its wording exists in the source text.
- Confirm that its language matches the original expression.
- Confirm that no translation or paraphrasing has occurred.
- Remove any keyword that cannot be verified directly against the source.
11. If a concept is semantically important but cannot be expressed using an actual phrase from the source text, DO NOT generate a new expression for it.
12. When multiple equivalent expressions appear in the source, prefer an expression that actually occurs in the text. Do not create a new normalized English or Persian expression.
VIOLATION OF THESE RULES IS NOT ACCEPTABLE.
LITERAL SOURCE FIDELITY TAKES PRIORITY OVER SEMANTIC REPHRASING.
# Output
Return only a valid JSON object with the following structure:
{{
"named_entities": [
{{
"keyword": "نام شخص یا موجودیت <فارسی مطابق با متن بدون هیچ گونه تغییری>",
"type": "PERSON | ORGANIZATION | LOCATION | DATE | EVENT | LAW | DOCUMENT | OTHER",
"ids": ["id1", "id2"]
}}
],
"legal_constraints": [
{{
"keyword": "<فارسی مطابق با متن بدون هیچ گونه تغییری> مفهوم قید یا حکم",
"type": "OBLIGATION | PROHIBITION | PERMISSION | CONDITION | EXCEPTION | DEADLINE | PENALTY | RIGHT | RESPONSIBILITY | LIMITATION | OTHER",
"ids": ["id1", "id2"]
}}
],
"topics_and_predicates": [
{{
"keyword": "<فارسی مطابق با متن بدون هیچ گونه تغییری> موضوع یا محمول استخراج‌شده؛ مکلف و فاعل و مجری و ...",
"type": "TOPIC | ACTION | PROCESS | STATE | PROPERTY | RELATION | OTHER",
"ids": ["id1", "id2"]
}}
]
}}
Return an empty array for categories with no extracted items.
# Input
Process all provided segments together while preserving their individual IDs."""
from collections import defaultdict
def repair_phase1(
system_prompt: str,
group_path=Path("/home1/ava3/data/elastic_search_indexes/mj_qa_group_v3.json"),
o_path=Path(
"/home1/ava3/project/aiDataParser/task/3form_keyword_qanon/input_qanon_repaired_phase2.json"
),
):
failed_ids = set(
i["id"]
for i in load_orjson(
"/home1/ava3/project/aiDataParser/task/3form_keyword_qanon/failed_data_qanon_keyword.json"
)
)
print(f"failed_ids {len(failed_ids)}")
f_data = defaultdict(list)
for item in load_orjson(group_path):
_id = item["_id"]
if _id in failed_ids:
_source = item["_source"]
qanon_id = _source["qanon_id"]
qanon_title = _source["qanon_title"]
content = _source["content"]
chunk_order = _source.get("chunk_order", 0)
f_data[qanon_id].append(
{
"qanon_title": qanon_title,
"content": content,
"chunk_id": _id,
"chunk_order": chunk_order,
}
)
print(f"f_data {len(f_data)}")
CHUNK_SIZE = 100
ff_data = []
for q_id, data in f_data.items():
print(f"data {len(data)}")
_qanon_title = data[0]["qanon_title"]
data = sorted(data, key=lambda x: x.get("chunk_order", 0))
# تقسیم به دسته‌های ۱۰۰تایی
for part, start in enumerate(range(0, len(data), CHUNK_SIZE), start=1):
batch = data[start : start + CHUNK_SIZE]
_text = "\n".join(f'{i["chunk_id"]}: {i["content"]}' for i in batch)
ff_data.append(
{
"id": f"{q_id}-{part}",
"used_ids": [i["chunk_id"] for i in batch],
"qanon_id": q_id,
"system_prompt": system_prompt,
"user_prompt": f"title:{_qanon_title}\n{_text}",
}
)
# break
print(f"ff_data {len(ff_data)}")
save_orjson(path=o_path, data=ff_data)
repair_phase1(system_prompt)
# python3 /home1/ava3/project/aiDataParser/task/3form_keyword_qanon/repair_qanon.py