From f67a9194a31090bd170f268e9129bd975b066bc9 Mon Sep 17 00:00:00 2001 From: hsafaei Date: Thu, 1 Jan 2026 06:59:21 +0000 Subject: [PATCH] be4 es-connect split-dev-from-deploy old-logic --- core/core.py | 12 ++++++-- router/bale/bale.py | 6 ++-- router/bale/bale_buttons.py | 3 +- router/bale/bale_handle.py | 59 +++++++++++++++++++++++++++++++------ router/bale/config.py | 28 +++++++++--------- 5 files changed, 79 insertions(+), 29 deletions(-) diff --git a/core/core.py b/core/core.py index 603154f..6fd0a0e 100755 --- a/core/core.py +++ b/core/core.py @@ -607,8 +607,8 @@ chat_id class RequestManager: def __init__(self, host_url:str, - url_time_out=120, - step_time_out=60, + url_time_out=1200, + step_time_out=600, ): self.host_url = host_url self.url_time_out = url_time_out @@ -914,6 +914,11 @@ def cer_ntlk(exist: str, new: str) -> float: # edit distance روی کلمات return round(float(1 - edit_distance(new, exist) / len(exist)) * 100, 2) +def wer_nltk(new: str, exist: str) -> float: + new = new.split() + exist = exist.split() + + return round(float(1 - edit_distance(new, exist) / len(exist)) * 100, 2) async def title_repeated( @@ -948,7 +953,8 @@ async def title_repeated( for i in data["hits"]["hits"]: title = i["_source"]["title"] ids.append( - {"title": title, "id": i["_source"]["id"], "score" :cer_ntlk(exist=title, new=qanontitle)} + {"title": title, "id": i["_source"]["id"], "score" :wer_nltk(exist=title, new=qanontitle)} + # {"title": title, "id": i["_source"]["id"], "score" :cer_ntlk(exist=title, new=qanontitle)} ) return sorted(ids, key=lambda x: x['score'], reverse=True)[:search_range] diff --git a/router/bale/bale.py b/router/bale/bale.py index 2f4a2cc..cb5aeee 100755 --- a/router/bale/bale.py +++ b/router/bale/bale.py @@ -18,15 +18,17 @@ async def webhook( bale_bot: BaleBot = Depends(_get_bale_bot), ): raw = await request.json() + # print(' webhook request ', raw) try: - update = BaleUpdate(**raw) + #تبدیل به آبجکت مدل + input_data = BaleUpdate(**raw) except Exception as e: print("❌ Parse Error", e) return {"ok": True} # print(f"update {update}") - return await bale_bot.render_update(update) + return await bale_bot.render_update(input_data) def initialize_webhook(webhook_url, set_webhook_url): diff --git a/router/bale/bale_buttons.py b/router/bale/bale_buttons.py index 753a3ef..304db48 100755 --- a/router/bale/bale_buttons.py +++ b/router/bale/bale_buttons.py @@ -1,7 +1,8 @@ BACK_BUTTON = {"text": "⬅️ مرحله قبل", "callback_data": "workflow_back"} HOME_BUTTON = {"text": "🏠 خانه", "callback_data": "main"} MORE_LIMIT_BUTTON = {"text": "بارگذاری نتایج بیشتر 10+", "callback_data": "more_limit"} -MORE_EFFORT_BUTTON = {"text": "🧠 بررسی عمیق تر", "callback_data": "more_effort"} +# MORE_EFFORT_BUTTON = {"text": "🧠 بررسی عمیق تر", "callback_data": "more_effort"} +MORE_EFFORT_BUTTON = {"text": "بررسی عمیق تر", "callback_data": "more_effort"} BUTTON_TEXT_TO_CALLBACK_LIST = [ {"text": "جستجو"}, diff --git a/router/bale/bale_handle.py b/router/bale/bale_handle.py index 110017d..9a1ad0b 100755 --- a/router/bale/bale_handle.py +++ b/router/bale/bale_handle.py @@ -111,6 +111,7 @@ class BaleBot: end_buttons=state_detail.end_buttons, ) return {"ok": True} + # if user.input_query != "" and not run_internal and if run_internal == "subject_unities": await self.handle_advanced_check_conflict(user) @@ -119,7 +120,7 @@ class BaleBot: handler = getattr(self, state_detail.handler) await handler(user) except: - await self.handle_main(user) + await self.handle_chat_in_law(user) return {"ok": True} @@ -418,6 +419,7 @@ class BaleBot: await self.send_message_helper(user=user, text=ERROR_IN_PROCESS) finally: + user.input_query = "" user.is_processing_lock = False return {"ok": True} @@ -425,6 +427,7 @@ class BaleBot: async def handle_rule_making(self, user: BaleUser): user.is_processing_lock = True + user.effort = "medium" try: result = await self.request_manager.get_result( payload={ @@ -435,18 +438,22 @@ class BaleBot: url="/rule_making", ) print(f"handle_rule_making {result}") + res_ = await self.formatter.form_rule_making(_input=result) + _buttons = [[HOME_BUTTON]] if user.effort != "medium": _buttons.append([MORE_EFFORT_BUTTON]) await self.send_message_helper( user=user, chunked_text=res_, end_buttons=_buttons ) + except Exception as e: print("ERROR in handle_chat:", str(traceback.print_exc())) await self.send_message_helper(user=user, text=ERROR_IN_PROCESS) finally: + user.input_query = "" user.is_processing_lock = False return {"ok": True} @@ -466,14 +473,38 @@ class BaleBot: await self.send_message_helper(user=user, text=ERROR_IN_PROCESS) finally: user.is_processing_lock = False + user.input_query = "" return {"ok": True} + async def handle_talk(self, user: BaleUser): + user.is_processing_lock = True + try: + result = await self.request_manager.get_result( + payload={ + "user_input": user.input_query, + }, + url="/talk", + ) + # answer + # answer_type + + await self.send_message_helper( + user=user, chunked_text=result['answer'], end_buttons=MAIN_BUTTON + ) + except Exception as e: + print("ERROR in handle_chat:", str(traceback.print_exc())) + await self.send_message_helper(user=user, text=ERROR_IN_PROCESS) + finally: + user.is_processing_lock = False + + return {"ok": True} + + async def handle_conflict_qanon_asasi(self, user: BaleUser): user.is_processing_lock = True user.last_message_id = 0 - user.effort = "medium" try: print(f"effort=user.effort {user.effort}") async for step_data in self.request_manager.stream_result( @@ -562,6 +593,7 @@ class BaleBot: await self.send_message_helper(user=user, text=ERROR_IN_PROCESS) finally: user.is_processing_lock = False + user.input_query = "" return {"ok": True} async def handle_conflict_law_writing_policy(self, user: BaleUser): @@ -593,6 +625,7 @@ class BaleBot: await self.send_message_helper(user=user, text=ERROR_IN_PROCESS) finally: + # user.input_query = "" user.is_processing_lock = False return {"ok": True} @@ -657,6 +690,7 @@ class BaleBot: await self.send_message_helper(user=user, text=ERROR_IN_PROCESS) finally: + # user.input_query = "" user.is_processing_lock = False return {"ok": True} @@ -723,6 +757,7 @@ class BaleBot: await self.send_message_helper(user=user, text=ERROR_IN_PROCESS) finally: + # user.input_query = "" user.is_processing_lock = False return {"ok": True} @@ -731,14 +766,17 @@ class BaleBot: user.is_processing_lock = True print(f"handle_advanced_check_conflict======================================") try: + print(f'user.call_back_query {user.call_back_query}') step, _type, qq_title = user.call_back_query.split(":") if _type == "qq": + print('A') groups = {} for qanon_title, item in user.subject_unities.items(): if qanon_title == qq_title: for i in item: groups[qanon_title] = i.db_rule.section_id + print('B') if len(groups) > 1: _button = [] for i, (k, v) in enumerate(groups.items(), start=1): @@ -752,8 +790,10 @@ class BaleBot: ) else: user.call_back_query = f"subject_unities:qs:{groups[qq_title]}" + print('ccccc') elif _type == "qs": + print('AAA@@@') content = None for k, v in user.subject_unities.items(): if v.db_rule.section_id == qq_title: @@ -816,6 +856,7 @@ class BaleBot: print("ERROR in handle_chat:", str(traceback.print_exc())) await self.send_message_helper(user=user, text=ERROR_IN_PROCESS) finally: + # user.input_query = "" user.is_processing_lock = False return {"ok": True} @@ -826,15 +867,12 @@ class BaleBot: user.is_processing_lock = True user.last_query = user.input_query - - # گرفتن آخرین runtime - effort = user.effort try: # اگر runtime تغییر کرده یا نتیجه قبلی وجود ندارد → درخواست جدید result = await self.request_manager.get_result( payload={ "section_content": user.input_query, - "effort": effort, + "effort": user.effort, "limit": user.limit, "mode_type": "bale", }, @@ -846,10 +884,11 @@ class BaleBot: ) _buttons = [[HOME_BUTTON]] _b = [] - if user.limit < self.max_limit: - _b += [MORE_LIMIT_BUTTON] + if result['answer_type'] == 'legal_question': + if user.limit < self.max_limit: + _b += [MORE_LIMIT_BUTTON] - if effort != "medium": + if user.effort != "medium": _b += [MORE_EFFORT_BUTTON] if len(_b) > 0: @@ -863,6 +902,7 @@ class BaleBot: print("ERROR in handle_chat:", str(traceback.print_exc())) await self.send_message_helper(user=user, text=ERROR_IN_PROCESS) finally: + user.input_query = "" user.is_processing_lock = False async def handle_stream_chat(self, user: BaleUser): @@ -957,6 +997,7 @@ class BaleBot: await self.send_message_helper(user=user, text=ERROR_IN_PROCESS) finally: + user.input_query = "" user.is_processing_lock = False return {"ok": True} diff --git a/router/bale/config.py b/router/bale/config.py index ddce9fc..57c028b 100644 --- a/router/bale/config.py +++ b/router/bale/config.py @@ -3,7 +3,7 @@ from router.bale.base_model import StateDetail -BUSY_TEXT = ("""⏳ تا اتمام پردازش قبلی منتظر بمانید ⏳""",) +BUSY_TEXT = ("""⏳ درخواست قبلی شما در حال پردازش هست، لطفا تا اتمام آن منتظر بمانید ⏳""",) class StateRegistry: @@ -30,42 +30,42 @@ STATE = [ state="chat_in_law", button_text="گفتگو طبق قوانین کشور", end_buttons=[], - message="""💬 با احترام، آماده گفتگو هستم""", + message="""💬 با احترام، آماده گفتگو هستم، لطفا سوال خود را بپرسید""", handler="handle_chat_in_law", ), StateDetail( state="logical_chat_in_law", - button_text="گفتگوی حقوقی دقیق تر 🧠💬", + button_text="گفتگو با متن حقوقی 💬", end_buttons=[], - message="""💬 با عرض ادب و احترام، آماده گفتگو حقوقی دقیق هستم""", + message="""💬 با عرض ادب و احترام، آماده گفتگو طبق یک متن حقوقی هستم، لطفا متن ماده یا تبصره وارد کنید""", handler="handle_logical_chat_in_law", ), StateDetail( state="conflict_law_writing_policy", button_text="بررسی مغایرت با سیاست های قانون گذاری 📜", end_buttons=[], - message="""متن مورد نظر برای بررسی مغایرت با سیاست های قانون گذاری را وارد کنید :""", + message="""لطفا متن قانونی مورد نظر برای بررسی مغایرت با سیاست های قانون گذاری را وارد کنید :""", handler="handle_conflict_law_writing_policy", ), StateDetail( state="conflict_qanon_asasi", button_text="بررسی مغایرت با اصول مهم قانون اساسی ⚖️", end_buttons=[], - message="""متن مورد نظر برای بررسی مغایرت با اصول مهم قانون اساسی را وارد کنید :""", + message="""لطفا متن قانونی مورد نظر برای بررسی مغایرت با اصول مهم قانون اساسی را وارد کنید :""", handler="handle_conflict_qanon_asasi", ), StateDetail( state="conflict_general_policy", button_text="بررسی مغایرت با سیاست های کلی نظام 🏛️", end_buttons=[], - message="""متن مورد نظر برای بررسی مغایرت با سیاست های کلی نظام را وارد کنید :""", + message="""لطفا متن قانونی مورد نظر برای بررسی مغایرت با سیاست های کلی نظام را وارد کنید :""", handler="handle_conflict_general_policy", ), StateDetail( state="conflict_all_qavanin", button_text="بررسی مغایرت در تمام قوانین", end_buttons=[], - message="""متن مورد نظر برای بررسی مغایرت در تمام قوانین جمهوری اسلامی ایران را وارد کنید :""", + message="""لطفا متن قانونی مورد نظر برای بررسی مغایرت در تمام قوانین جمهوری اسلامی ایران را وارد کنید :""", handler="handle_conflict_all_qavanin", ), StateDetail( @@ -78,16 +78,16 @@ STATE = [ StateDetail( state="rule_making", handler="handle_rule_making", - button_text="استخراج اجزاء حقوقی متن", + button_text="استخراج اجزاء متن", end_buttons=[], - message="""متن مورد نظر برای استخراج اجزاء حقوقی را وارد کنید :""", + message="""خوبه، لطفا متن مورد نظر برای استخراج اجزاء حقوقی را وارد کنید :""", ), StateDetail( state="beta", - handler="handle_beta", + handler="handle_talk", button_text="BETA-Mode", end_buttons=[], - message="""این قسمت در دست توسعه قرار دارد ...""", + message="""""", ), StateDetail( state="contact_us", @@ -132,15 +132,15 @@ def build_buttons_form(button_form): # Button-STYLE main_button_form = [ - ["search_in_law"], ["chat_in_law"], + ["search_in_law"], ["logical_chat_in_law"], ["rule_making"], + ["qanon_title_repeat"], ["conflict_law_writing_policy"], ["conflict_qanon_asasi"], ["conflict_general_policy"], ["conflict_all_qavanin"], - ["qanon_title_repeat"], ["contact_us", "about_us", "beta"] ] MAIN_BUTTON = build_buttons_form(main_button_form) \ No newline at end of file