app_in_browser.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. import importlib
  2. import json
  3. import os
  4. import sys
  5. from pathlib import Path
  6. import gradio as gr
  7. import jsonlines
  8. import config_browserqwen
  9. sys.path.insert(
  10. 0,
  11. str(Path(__file__).absolute().parent.parent)) # NOQA
  12. from qwen_agent.actions import Simple # NOQA
  13. from qwen_agent.memory import Memory # NOQA
  14. prompt_lan = sys.argv[1]
  15. llm_name = sys.argv[2]
  16. max_ref_token = int(sys.argv[3])
  17. model_server = sys.argv[4]
  18. api_key = sys.argv[5]
  19. server_host = sys.argv[6]
  20. if llm_name.startswith('gpt'):
  21. module = 'qwen_agent.llm.gpt'
  22. llm = importlib.import_module(module).GPT(llm_name)
  23. elif llm_name.startswith('Qwen') or llm_name.startswith('qwen'):
  24. module = 'qwen_agent.llm.qwen'
  25. llm = importlib.import_module(module).Qwen(llm_name, model_server=model_server, api_key=api_key)
  26. else:
  27. raise NotImplementedError
  28. mem = Memory(config_browserqwen.similarity_search, config_browserqwen.similarity_search_type)
  29. cache_file = os.path.join(config_browserqwen.cache_root, config_browserqwen.browser_cache_file)
  30. cache_file_popup_url = os.path.join(config_browserqwen.cache_root, config_browserqwen.url_file)
  31. PAGE_URL = []
  32. with open(Path(__file__).resolve().parent / 'css/main.css', 'r') as f:
  33. css = f.read()
  34. with open(Path(__file__).resolve().parent / 'js/main.js', 'r') as f:
  35. js = f.read()
  36. def add_text(history, text):
  37. history = history + [(text, None)]
  38. return history, gr.update(value='', interactive=False)
  39. def rm_text(history):
  40. if not history:
  41. gr.Warning('No input content!')
  42. elif not history[-1][1]:
  43. return history, gr.update(value='', interactive=False)
  44. else:
  45. history = history[:-1] + [(history[-1][0], None)]
  46. return history, gr.update(value='', interactive=False)
  47. def add_file(history, file):
  48. history = history + [((file.name, ), None)]
  49. return history
  50. def set_page_url():
  51. lines = []
  52. assert os.path.exists(cache_file_popup_url)
  53. for line in jsonlines.open(cache_file_popup_url):
  54. lines.append(line)
  55. PAGE_URL.append(lines[-1]['url'])
  56. print('now page url is: ', PAGE_URL[-1])
  57. def bot(history):
  58. set_page_url()
  59. if not history:
  60. yield history
  61. else:
  62. now_page = None
  63. _ref = ''
  64. if not os.path.exists(cache_file):
  65. gr.Info("Please add this page to Qwen's Reading List first!")
  66. else:
  67. for line in jsonlines.open(cache_file):
  68. if line['url'] == PAGE_URL[-1]:
  69. now_page = line
  70. if not now_page:
  71. gr.Info("This page has not yet been added to the Qwen's reading list!")
  72. elif not now_page['raw']:
  73. gr.Info('Please wait, Qwen is analyzing this page...')
  74. else:
  75. _ref_list = mem.get(history[-1][0], [now_page], llm=llm, stream=False, max_token=max_ref_token)
  76. if _ref_list:
  77. _ref = '\n'.join(json.dumps(x, ensure_ascii=False) for x in _ref_list)
  78. else:
  79. _ref = ''
  80. # print(_ref)
  81. agent = Simple(stream=True, llm=llm)
  82. history[-1][1] = ''
  83. response = agent.run(_ref, history, prompt_lan=prompt_lan)
  84. for chunk in response:
  85. history[-1][1] += chunk
  86. yield history
  87. # save history
  88. if now_page:
  89. now_page['session'] = history
  90. lines = []
  91. for line in jsonlines.open(cache_file):
  92. if line['url'] != PAGE_URL[-1]:
  93. lines.append(line)
  94. lines.append(now_page)
  95. with jsonlines.open(cache_file, mode='w') as writer:
  96. for new_line in lines:
  97. writer.write(new_line)
  98. def load_history_session(history):
  99. now_page = None
  100. if not os.path.exists(cache_file):
  101. gr.Info("Please add this page to Qwen's Reading List first!")
  102. return []
  103. for line in jsonlines.open(cache_file):
  104. if line['url'] == PAGE_URL[-1]:
  105. now_page = line
  106. if not now_page:
  107. gr.Info("Please add this page to Qwen's Reading List first!")
  108. return []
  109. if not now_page['raw']:
  110. gr.Info('Please wait, Qwen is analyzing this page...')
  111. return []
  112. return now_page['session']
  113. def clear_session():
  114. if not os.path.exists(cache_file):
  115. return None
  116. now_page = None
  117. lines = []
  118. for line in jsonlines.open(cache_file):
  119. if line['url'] == PAGE_URL[-1]:
  120. now_page = line
  121. else:
  122. lines.append(line)
  123. if not now_page:
  124. return None
  125. now_page['session'] = []
  126. lines.append(now_page)
  127. with jsonlines.open(cache_file, mode='w') as writer:
  128. for new_line in lines:
  129. writer.write(new_line)
  130. return None
  131. with gr.Blocks(css=css, theme='soft') as demo:
  132. chatbot = gr.Chatbot([],
  133. elem_id='chatbot',
  134. height=480,
  135. avatar_images=(None, (os.path.join(
  136. Path(__file__).resolve().parent, 'img/logo.png'))))
  137. with gr.Row():
  138. with gr.Column(scale=7):
  139. txt = gr.Textbox(show_label=False,
  140. placeholder='Chat with Qwen...',
  141. container=False)
  142. # with gr.Column(scale=0.06, min_width=0):
  143. # smt_bt = gr.Button('⏎')
  144. with gr.Column(scale=1, min_width=0):
  145. clr_bt = gr.Button('🧹', elem_classes='bt_small_font')
  146. with gr.Column(scale=1, min_width=0):
  147. stop_bt = gr.Button('🚫', elem_classes='bt_small_font')
  148. with gr.Column(scale=1, min_width=0):
  149. re_bt = gr.Button('🔁', elem_classes='bt_small_font')
  150. txt_msg = txt.submit(add_text, [chatbot, txt], [chatbot, txt],
  151. queue=False).then(bot, chatbot, chatbot)
  152. txt_msg.then(lambda: gr.update(interactive=True), None, [txt], queue=False)
  153. # txt_msg_bt = smt_bt.click(add_text, [chatbot, txt], [chatbot, txt],
  154. # queue=False).then(bot, chatbot, chatbot)
  155. # txt_msg_bt.then(lambda: gr.update(interactive=True),
  156. # None, [txt],
  157. # queue=False)
  158. clr_bt.click(clear_session, None, chatbot, queue=False)
  159. re_txt_msg = re_bt.click(rm_text, [chatbot], [chatbot, txt], queue=False).then(bot, chatbot, chatbot)
  160. re_txt_msg.then(lambda: gr.update(interactive=True), None, [txt], queue=False)
  161. stop_bt.click(None, None, None, cancels=[txt_msg, re_txt_msg], queue=False)
  162. demo.load(set_page_url).then(load_history_session, chatbot, chatbot)
  163. demo.queue().launch(server_name=server_host, server_port=config_browserqwen.app_in_browser_port)