tối ưu đoạn mã sau: import json import time from playwright.syncapi import…
- User
tối ưu đoạn mã sau: import json import time from playwright.sync_api import sync_playwright
class ChatBot: def init(self): self.CAU_CU = 'trong' self.CAU_TONG = '' self.TUKHOA = 'ketthuc' self.isLoi = False self.playwright = None self.browser = None
def daSuyNghiXong(self, page): daSuyNghi = False while not daSuyNghi: time.sleep(.5) try: input_element = page.locator("#prompt") # Lấy giá trị thuộc tính 'disabled' is_disabled = input_element.get_attribute("disabled") if is_disabled == '': return False if is_disabled is None: daSuyNghi = True return True except: return False def doc(self, cau, page): time.sleep(1) LOI = 'something went wrong' # loi = False while 1: if self.daSuyNghiXong(page): # Sử dụng Selectors để tìm div có class là "message p-2" content_textss = page.locator('div.message.p-2').all() content_text = content_textss[-1] if len(content_textss) > 1 else content_textss[0] # Trích xuất nội dung của div content_texts = content_text.text_content() if LOI in content_texts: self.isLoi = True break else: content_texts = content_texts.splitlines() ket_qua = [i for i in content_texts if len(i) > 0] ket_qua = ket_qua if len(ket_qua) <= 1 else ket_qua[:-1] for kq in ket_qua: print(kq.split(cau)[1]) if cau in kq else print(kq) break return self.isLoi def inputs(self): print('NHẬP CÂU HỎI CỦA BẠN:') CAU = '' cau = '' while not cau == self.TUKHOA: try: cau = input('-> ') if CAU == '' and cau != '': CAU = cau elif cau != '': CAU = CAU + '. ' + cau except: pass self.CAU_TONG = self.CAU_TONG + CAU return 'bằng tiếng việt, trả lời '+CAU def nhap_cau_hoi(self): return self.inputs() def send_luna(self, cau, page): page.get_by_placeholder("Enter your question...").click() page.get_by_placeholder("Enter your question...").fill(cau) page.get_by_placeholder("Enter your question...").press("Enter") def reset_page(self, context, page): page.close() context.clear_cookies() context.clear_permissions() context.close() def run_0(self): while True: context = self.browser.new_context() page = context.new_page() page.goto("https://opnai.net/") time.sleep(3) with open(f'cookies.json',"a") as f: f.write(json.dumps(context.cookies())) f.write('\n') isLoi = False while True: if self.CAU_CU == 'trong': cau = self.nhap_cau_hoi() else: cau = self.CAU_CU self.CAU_CU = 'trong' cau = cau.replace(self.TUKHOA, '') # # try: # self.isLoi = self.doc(cau, page) # except: # pass if cau.lower() != 'ket thuc.' and cau != '': if not self.isLoi: self.send_luna(cau=cau, page=page) self.isLoi = self.doc(cau, page) if self.isLoi: self.CAU_CU = cau break else: print('Đợi tôi một chút...') self.CAU_CU = cau break if self.isLoi: self.reset_page(context=context, page=page) self.CAU_CU = self.CAU_TONG.replace(self.TUKHOA, '') self.isLoi = False # self.CAU_TONG = '' def run(self): self.CAU_CU = 'trong' self.CAU_TONG = '' with sync_playwright() as self.playwright: self.browser = self.playwright.chromium.launch(headless=False) while True: self.run_0() # self.browser.close()if name == "main": chat_bot = ChatBot() chat_bot.run()
- Assistant
To optimize the given code, we can focus on several aspects such as improving code readability, reducing redundancy, using proper exception handling, and adhering to best practices for synchronization and performance. Here are some optimizations that could be made:
- Avoid hard-coded sleep statements where possible in favor of more deterministic wait conditions.
- Use context managers to handle resources like files.
- Remove unused or commented code.
- Simplify the structure and flow of loops and conditions.
- Use more descriptive variable names.
- Consolidate repeated code into functions.
- Use exception handling to capture specific errors rather than using a general
exceptstatement.
Here's an optimized version of the code with some of these improvements.
import json from playwright.sync_api import sync_playwright class ChatBot: def __init__(self): self.pending_question = 'empty' self.cumulative_question = '' self.keyword_end = 'ketthuc' self.error_encountered = False self.playwright = None self.browser = None def has_finished_thinking(self, page): # Waits for input prompt to be enabled input_element = page.locator("#prompt") is_disabled = input_element.get_attribute("disabled") return is_disabled is None def read_response(self, question, page): error_message = 'something went wrong' page.wait_for_selector('div.message.p-2') content_texts = page.locator('div.message.p-2').all_texts() latest_response = content_texts[-1] if len(content_texts) > 1 else content_texts[0] if error_message in latest_response.lower(): self.error_encountered = True return for response in latest_response.splitlines(): if question in response: print(response.split(question)[1]) else: print(response) def prompt_for_question(self): print('Please enter your question:') full_question = '' while True: user_input = input('-> ').strip() if user_input: if full_question: full_question += '. ' + user_input else: full_question = user_input if self.keyword_end in user_input.lower(): break self.cumulative_question += full_question return 'by speaking Vietnamese, answer ' + full_question def send_query(self, question, page): query_input = page.locator("input[placeholder='Enter your question...']") query_input.click() query_input.fill(question) query_input.press("Enter") def reset_page(self, context): context.close() def interact_with_chat(self, context): page = context.new_page() page.goto("https://opnai.net/") while not self.error_encountered: question = self.pending_question if self.pending_question != 'empty' else self.prompt_for_question() question = question.replace(self.keyword_end, '') if 'ket thuc.' not in question.lower() and question: self.send_query(question, page) if self.has_finished_thinking(page): self.read_response(question, page) if self.error_encountered: self.pending_question = question break else: print('Please wait...') def run_bot(self): while True: with self.browser.new_context() as context, open('cookies.json', "a") as cookies_file: self.interact_with_chat(context) cookies = json.dumps(context.cookies()) cookies_file.write(cookies + '\n') if self.error_encountered: self.reset_page(context) self.pending_question = self.cumulative_question.replace(self.keyword_end, '') self.error_encountered = False def run(self): with sync_playwright() as self.playwright: self.browser = self.playwright.chromium.launch(headless=False) self.run_bot() if __name__ == "__main__": chat_bot = ChatBot() chat_bot.run()This code isn't fully tested, but it should give you an idea of how you might start to refactor and optimize the script. Remember that interactions with web pages can often be better handled with explicit wait conditions rather than timed sleeps, and using the browser's dev tools could help you identify better ways to interact with elements on the page.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.