llama/elastic_keywords_llama3.py
2025-07-13 19:05:59 +03:30

167 lines
7.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from html import escape
from lxml import etree
from datetime import datetime
from elasticsearch import Elasticsearch
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline, TextIteratorStreamer
from threading import Thread
import torch
#from cleantext import clean
#import re
if torch.cuda.is_available():
model_id = "PartAI/Dorna-Llama3-8B-Instruct"
model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", torch_dtype=torch.bfloat16)
tokenizer = AutoTokenizer.from_pretrained(model_id)
pipe = pipeline(
"text-generation",
model=model,
tokenizer=tokenizer,
torch_dtype=torch.float16,
device_map="auto",
)
index_name_i = 'semantic_search-v10'
es = Elasticsearch(
"http://127.0.0.1:6900",
# ca_certs="/path/to/http_ca.crt",
basic_auth=("elastic", "SG*7eGwg+KG2_*-1_mMm")
)
counter = 0
total = 0
id = ''
messages = [ {'role': 'user', 'content': 'لطفا فقط فارسی جواب بدهید'},
{'role': 'user', 'content': '''
متن شماره 1:
برای تأمین استقلال اقتصادی جامعه و ریشه ‌كن كردن فقر و محرومیت و برآوردن نیازهای انسان در جریان رشد، با حفظ آزادگی او، اقتصاد جمهوری اسلامی ایران بر اساس ضوابط زیر استوار می ‌شود:
۱- تأمین نیازهای اساسی: مسكن، خوراك، پوشاك، بهداشت، درمان، آموزش و پرورش و امكانات لازم برای تشكیل خانواده برای همه.
۲- تأمین شرایط و امكانات كار برای همه به منظور رسیدن به اشتغال كامل و قرار دادن وسایل كار در اختیار همه كسانی كه قادر به كارند ولی وسایل كار ندارند، در شكل تعاونی، از راه وام بدون بهره یا هر راه مشروع دیگر كه نه به تمركز و تداول ثروت در دست افراد و گروه های خاص منتهی شود و نه دولت را به صورت یك كارفرمای بزرگ مطلق درآورد. این اقدام باید با رعایت ضرورت های حاكم بر برنامه ‌ریزی عمومی اقتصاد كشور در هر یك از مراحل رشد صورت گیرد.
۳- تنظیم برنامه اقتصادی كشور به صورتی كه شكل و محتوا و ساعات كار چنان باشد كه هر فرد علاوه بر تلاش شغلی ، فرصت و توان كافی برای خودسازی معنوی، سیاسی و اجتماعی و شركت فعال در رهبری كشور و افزایش مهارت و ابتكار داشته باشد.
۴- رعایت آزادی انتخاب شغل و عدم اجبار افراد به كاری معین و جلوگیری از بهره‌ كشی از كار دیگری.
۵- منع اضرار به غیر و انحصار و احتكار و ربا و دیگر معاملات باطل و حرام.
متن شماره 1، کلیدواژه های اصلی عبارتن اند از:
تأمین استقلال اقتصادی
برآوردن نیازهای انسان
حفظ آزادگی
نیازهای اساسی
تشكیل خانواده
اشتغال
تعاونی
وام بدون بهره
تمرکز ثروت
برنامه ‌ریزی عمومی اقتصاد
برنامه اقتصادی كشور
آزادی انتخاب شغل
منع اضرار به غیر
منع احتکار
منع انحصار
منع ربا
منع معاملات باطل و حرام
'''}
]
def es_iterate_all_documents(es, index, pagesize=250, scroll_timeout="12m", **kwargs):
"""
Helper to iterate ALL values from a single index
Yields all the documents.
"""
global counter
global total
is_first = True
while True:
# Scroll next
if is_first: # Initialize scroll
# result = es.search(index=index, scroll="12m", **kwargs, body={
# "size": pagesize
# })
result = es.search(index=index, scroll="12m", **kwargs, size=pagesize)
total = result["hits"]["total"]['value']
print('total = %d' % total)
is_first = False
else:
# result = es.scroll(body={
# "scroll_id": scroll_id,
# "scroll": scroll_timeout
# })
result = es.scroll( scroll_id = scroll_id, scroll = scroll_timeout )
scroll_id = result["_scroll_id"]
hits = result["hits"]["hits"]
counter += len(hits)
print("progress -> %.2f %% , counte: %d" % ((counter / total)*100, counter))
# Stop after no more docs
if not hits:
break
# Yield each entry
yield from ({"source":hit['_source'], "id":hit['_id']} for hit in hits)
try:
#els_file = open('./elastic-dataset.jsonl', 'w', encoding='utf-8')
for mentry in es_iterate_all_documents(es, index_name_i):
entry = mentry['source']
id = mentry['id']
#title = entry.get('title','').replace('"', "'").replace('\n', ' ').replace('\r', '')
text = entry.get('clean_content','')
#lkeys = entry.get('content_keywords','')
print("%s -> %.2f " % (id , counter / total))
try:
message_new = {"role": "user", "content":
'''
با توجه به کلیدواژه های استخراج شده از متن شماره 1
از متن زیر حداقل 15 کلیدواژه اصلی را استخراج کن به طوریکه تعداد توکن های هر کلیدواژه حداقل بین 1 تا 5 توکن باشد: {}
'''.format(text)
}
messages.append(message_new)
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
outputs = pipe(prompt,
max_new_tokens=512,
do_sample=True,
temperature=0.7,
#num_return_sequences=1,
#eos_token_id=tokenizer.eos_token_id,
#max_length=4096, # max lenght of output, default=4096
return_full_text=False, # to not repeat the question, set to False
top_k=50,
top_p=0.95)
keywords = outputs[0]["generated_text"]
#print(lkeys)
#print(keywords)
#print('*'*20)
resp = es.update(index=index_name_i, id=id, doc={"content_keywords-llama3-str": str(keywords)})
messages.pop()
except Exception as inst:
print(type(inst)) # the exception type
print(inst.args) # arguments stored in .args
print("Exception: " + str(inst))
# print(inst)
# print(id)
except Exception as inst:
print(type(inst)) # the exception type
print(inst.args) # arguments stored in .args
print(inst) # __str__ allows args to be printed directly,
# but may be overridden in exception subclasses
print("%s -> %.2f " % (id , counter / total))