303 lines
13 KiB
Python
303 lines
13 KiB
Python
import os, re
|
|
import orjson
|
|
from pathlib import Path
|
|
import json, traceback
|
|
import re
|
|
from typing import Any
|
|
from pydantic import BaseModel
|
|
from typing import List, Dict, Optional
|
|
from collections import defaultdict
|
|
|
|
|
|
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)
|
|
)
|
|
|
|
|
|
jokar_prompt = """
|
|
شما یک تحلیلگر حقوقی خبره و مسلط به روش کیفی تحلیل مضمون در متون حقوقی و قانونی هستید. وظیفه شما استخراج مضامین پایه حقوقی از پاراگراف زیر است.
|
|
|
|
پاراگراف:
|
|
{content}
|
|
|
|
قوانین استخراج مضمون:
|
|
1. مضامین باید عبارات معنایی دقیق و تیز باشند (یک تا چند کلمه).
|
|
2. از مضامین خیلی کلی و عمومی (مثل "تأثیر"، "مشکل"، "راهکار") پرهیز کنید.
|
|
3. هر مضمون پایه، توصیف محتوایی کاملی باشد که به تنهایی معنادار باشد.
|
|
4. تعداد کلمات هر مضمون پایه از 3 کلمه کمتر نشود
|
|
5. هر مضمون باید مستقیماً از متن استخراج شود و نشاندهنده یک مفهوم کلیدی باشد.
|
|
6. اگر متن شامل چند مفهوم کلیدی است، همه را استخراج کنید. اما سعی شود که کمترین تعداد مضمونی که نماینده معنایی کاملی از متن باشد استخراج شود.
|
|
|
|
7. اگر متن فاقد مضمون محتوایی است، لیست خالی برگردانید.
|
|
|
|
خروجی را فقط به صورت یک لیست از رشتهها (string) بنویسید که با [ شروع و با ] خاتمه مییابد.
|
|
مثال خروجی: ["نماز جمعه به مثابه کانون هدایت فکری", "نقش موثر امام جمعه در هدایت معنوی", "راه اندازی مرکز امداد فرهنگی"]
|
|
|
|
خروجی شما:
|
|
"""
|
|
|
|
|
|
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."""
|
|
|
|
|
|
def creat_data(
|
|
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/data/qanon_phase2_in_data.json"
|
|
),
|
|
):
|
|
|
|
process_ids = set(
|
|
i["id"]
|
|
for i in load_orjson(
|
|
"/home1/ava3/project/aiDataParser/task/3form_keyword_qanon/data/Mistral-Small-4-119B/final_data_kw3.json"
|
|
)
|
|
)
|
|
print(f"process_ids {len(process_ids)}")
|
|
f_data = defaultdict(list)
|
|
for item in load_orjson(group_path):
|
|
_id = item["_id"]
|
|
_source = item["_source"]
|
|
qanon_id = _source["qanon_id"]
|
|
|
|
if qanon_id in process_ids:
|
|
continue
|
|
|
|
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}",
|
|
"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)
|
|
|
|
|
|
def creat_data_mashruh(
|
|
system_prompt: str,
|
|
group_paths=Path(
|
|
"/home1/ava3/project/aiDataParser/task/3form_keyword_qanon/in_data/"
|
|
),
|
|
o_path=Path(
|
|
"/home1/ava3/project/aiDataParser/task/3form_keyword_qanon/majles_group_mashruh_new_phase.json"
|
|
),
|
|
):
|
|
|
|
f_data = defaultdict(lambda: defaultdict(list))
|
|
|
|
for group_path in group_paths.rglob("*.json"):
|
|
for item in load_orjson(group_path):
|
|
source = item["_source"]
|
|
|
|
f_data[source["meet_date"]][source["dastur_number"]].append(
|
|
{
|
|
"id": item["_id"],
|
|
"dastur_number": source["dastur_number"],
|
|
"order": source["order"],
|
|
"meet_date": source["meet_date"],
|
|
"content": source["content"],
|
|
"title": source["title"],
|
|
}
|
|
)
|
|
|
|
print(f"f_data: {len(f_data)}")
|
|
|
|
ff_data = []
|
|
|
|
for meet_date, dastur_groups in sorted(f_data.items()):
|
|
for dastur_number, data in sorted(dastur_groups.items()):
|
|
|
|
data.sort(key=lambda x: int(x.get("order") or 0))
|
|
|
|
title = data[0]["title"]
|
|
|
|
_text = "\n".join(f'{i["id"]}: {i["content"]}' for i in data)
|
|
|
|
ff_data.append(
|
|
{
|
|
"id": f"{meet_date}|{dastur_number}",
|
|
"used_ids": [i["id"] for i in data],
|
|
"system_prompt": system_prompt,
|
|
"user_prompt": f"""title: {title}\n\t{_text}""",
|
|
}
|
|
)
|
|
# break
|
|
# break
|
|
|
|
print(f"ff_data {len(ff_data)}")
|
|
save_orjson(path=o_path, data=ff_data)
|
|
|
|
|
|
creat_data_mashruh(
|
|
# creat_data(
|
|
system_prompt
|
|
)
|
|
# python3 /home1/ava3/project/aiDataParser/task/3form_keyword_qanon/create_data.py
|