You-shen commited on
Commit
a4d78e2
·
verified ·
1 Parent(s): e7f2918

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -52
app.py CHANGED
@@ -26,12 +26,13 @@ from css import *
26
  os.environ["REPLICATE_API_TOKEN"] = "r8_IYJpjwjrxegcUfBeBbyUxErJXXsnHDM4AlSQQ"
27
  os.environ["OPENAI_API_KEY"] = "sb-6a683cb3bd63a9b72040aa2dd08feff8b68f08a0e1d959f5"
28
  os.environ['OPENAI_BASE_URL'] = "https://api.openai-sb.com/v1/"
29
- os.environ["SERPAPI_API_KEY"] = "dcc98b22d5f7d413979a175ff7d75b721c5992a3ee1e2363020b2bbdf4f82404" #you
30
  # os.environ['TAVILY_API_KEY'] = "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" #you
31
- os.environ['TAVILY_API_KEY'] = "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" #zeng
32
- image_path = "C:/Users/Lenovo/Desktop/demo-repository-master/image/img_2.png"
33
  model = ChatOpenAI(model_name="gpt-4", temperature=0.6)
34
 
 
35
  def search_baidu(query) -> str:
36
  params = {
37
  "engine": "baidu_news",
@@ -50,6 +51,7 @@ def search_baidu(query) -> str:
50
  ])
51
  return final_output
52
 
 
53
  def search_bing(query) -> str:
54
  params = {
55
  "engine": "bing_news",
@@ -68,6 +70,7 @@ def search_bing(query) -> str:
68
  ])
69
  return final_output
70
 
 
71
  def img_size(image):
72
  # img = Image.open(image)
73
  img = Image.fromarray(image.astype("uint8"))
@@ -81,40 +84,42 @@ def img_size(image):
81
  # resized_img.save(image_path)
82
  return resized_img
83
 
84
- def search_image(query)->str:
 
85
  params = {
86
- "engine": "google_images",
87
- "q": query,
88
- "gl": "cn",
89
  }
90
  search = GoogleSearch(params)
91
  results = search.get_dict()
92
  thumbnails = [search['thumbnail'] for search in results['suggested_searches']][:3]
93
- information=""
94
  client = OpenAI()
95
  for idx, thumbnail in enumerate(thumbnails):
96
- response = client.chat.completions.create(
97
- model="gpt-4o-mini",
98
- messages=[
99
- {
100
- "role": "user",
101
- "content": [
102
- {"type": "text", "text": "What’s in this image?Give a brief answer"},
103
- {
104
- "type": "image_url",
105
- "image_url": {
106
- "url": thumbnail,
107
- },
108
- },
 
 
109
  ],
110
- }
111
- ],
112
- max_tokens=100,
113
- )
114
- response_content = response.choices[0].message.content
115
- information = information + str(idx + 1) +": "+response_content + "\n"
116
  return (information)
117
 
 
118
  search_baidu = Tool(
119
  name="Baidu News Search", # 工具名称
120
  func=search_baidu, # 引用search函数
@@ -132,6 +137,8 @@ search_image = Tool(
132
  func=search_image, # 引用search函数
133
  description="搜索图片引擎,当你需要检索相关图片的时候调用,输入是检索query,输出是与query有关的图片的信息" # 工具描述
134
  )
 
 
135
  class ReplicateModel:
136
  def __init__(self, model_name: str):
137
  self.model_name = model_name
@@ -144,6 +151,7 @@ class ReplicateModel:
144
  )
145
  return output
146
 
 
147
  class DialogueAgent:
148
  def __init__(
149
  self,
@@ -179,6 +187,7 @@ class DialogueAgent:
179
  """
180
  self.message_history.append(f"{name}: {message}")
181
 
 
182
  class Replicate_DialogueAgent:
183
  def __init__(
184
  self,
@@ -218,6 +227,8 @@ class Replicate_DialogueAgent:
218
  Concatenates {message} spoken by {name} into message history
219
  """
220
  self.message_history.append(f"{name}: {message}")
 
 
221
  class DialogueSimulator:
222
  def __init__(
223
  self,
@@ -259,6 +270,7 @@ class DialogueSimulator:
259
 
260
  return speaker.name, message
261
 
 
262
  class Replicate_DialogueSimulator:
263
  def __init__(
264
  self,
@@ -300,6 +312,7 @@ class Replicate_DialogueSimulator:
300
 
301
  return speaker.name, message
302
 
 
303
  class DialogueAgentWithTools(DialogueAgent):
304
  def __init__(self, name: str, system_message: SystemMessage, model: ChatOpenAI, tools: List[BaseTool]):
305
  super().__init__(name, system_message, model)
@@ -313,13 +326,18 @@ class DialogueAgentWithTools(DialogueAgent):
313
  verbose=True,
314
  memory=ConversationBufferMemory(memory_key="chat_history", return_messages=True),
315
  )
316
- response = agent_chain.invoke(
317
- {"input": "\n".join([self.system_message.content] + self.message_history + [self.prefix])}
318
- )
 
 
 
319
  return response
320
 
 
321
  class Repliacte_DialogueAgentWithTools(Replicate_DialogueAgent):
322
- def __init__(self, name: str, system_message: SystemMessage, replicate_model: ReplicateModel, tools: List[BaseTool]):
 
323
  super().__init__(name, system_message, None) # 不再使用 ChatOpenAI 模型
324
  self.replicate_model = replicate_model # 存储 Replicate 模型
325
  self.tools = tools # 手动传递工具
@@ -333,12 +351,14 @@ class Repliacte_DialogueAgentWithTools(Replicate_DialogueAgent):
333
  response = self.replicate_model.predict(input_data)
334
  return response
335
 
 
336
  ddg_search = DuckDuckGoSearchResults()
337
  arxiv_query = ArxivQueryRun()
338
  tavily_tool = TavilySearchResults(max_result=2)
339
 
340
  tools = [tavily_tool, search_baidu]
341
 
 
342
  def select_next_speaker(step: int, agents: List[DialogueAgent]) -> int:
343
  idx = step % len(agents)
344
  return idx
@@ -368,7 +388,8 @@ def generate_agent_description(name, conversation_description, word_limit):
368
  agent_description = ChatOpenAI(temperature=1.0)(agent_specifier_prompt).content
369
  return agent_description
370
 
371
- def generate_system_message_ch(name, description, tools, topic,img_information):
 
372
  return f"""Here is the topic of discussion: {topic}
373
  Your name is {name}.
374
 
@@ -419,7 +440,8 @@ DO NOT make assumptions without evidence.
419
  Stop speaking the moment you finish your evaluation.
420
  """
421
 
422
- def generate_system_message_en(name, description, tools, topic,img_information):
 
423
  return f"""Here is the topic of discussion: {topic}
424
  Your name is {name}.
425
 
@@ -469,6 +491,8 @@ DO NOT make assumptions without evidence.
469
 
470
  Stop speaking the moment you finish your evaluation.
471
  """
 
 
472
  def encode_image(image):
473
  image = Image.fromarray(image.astype("uint8"))
474
  buffered = io.BytesIO()
@@ -477,6 +501,7 @@ def encode_image(image):
477
  # with open(image_path, "rb") as image_file:
478
  # return base64.b64encode(image_file.read()).decode("utf-8")
479
 
 
480
  def image_summarize(img_base64, prompt):
481
  chat = ChatOpenAI(model="gpt-4o", max_tokens=256)
482
  msg = chat.invoke(
@@ -494,6 +519,7 @@ def image_summarize(img_base64, prompt):
494
  )
495
  return msg.content
496
 
 
497
  def generate_img_summaries(image):
498
  # img_size(path)
499
  image_summaries = []
@@ -504,15 +530,21 @@ def generate_img_summaries(image):
504
  image_summaries.append(image_summarize(base64_image, prompt))
505
  return image_summaries
506
 
 
507
  selected_language = "ch"
508
  selected_model = "gpt"
 
 
509
  def SelectLanguage(option):
510
  global selected_language
511
  if option == "英文":
512
  selected_language = "en"
513
  else:
514
  selected_language = "ch"
515
- language_option = ["中文","英文"]
 
 
 
516
 
517
  def SelectModel(option):
518
  global selected_model
@@ -524,7 +556,10 @@ def SelectModel(option):
524
  selected_model = "llama3-8b"
525
  else:
526
  selected_model = "mistral"
527
- model_option = ["gpt-4o","llama3-70b","llama3-8b","mistral"]
 
 
 
528
 
529
  def start(topic, image_summaries):
530
  max_iters = 3
@@ -538,7 +573,8 @@ def start(topic, image_summaries):
538
  conversation_description = f"""Here is the news of conversation: {topic}
539
  The participants are: {', '.join(names.keys())}"""
540
 
541
- agent_descriptions = {name: generate_agent_description(name, conversation_description, word_limit) for name in names}
 
542
  if selected_language == "ch":
543
  agent_system_messages = {
544
  name: generate_system_message_ch(name, description, tools, topic, image_summaries)
@@ -580,7 +616,7 @@ def start(topic, image_summaries):
580
  simulator.inject("Moderator", specified_topic)
581
  while n < max_iters:
582
  name, message = simulator.step()
583
- result = result + "(" + name + "): " +message['output'] + "\n"
584
  # print(f"({name}): {message['output']}")
585
  # print("\n")
586
  n += 1
@@ -617,32 +653,51 @@ def start(topic, image_summaries):
617
  return result
618
 
619
 
 
 
620
  title = "# 虚假信息检测"
621
 
622
  with gr.Blocks(css=css1) as demo:
623
  gr.Markdown(title, elem_id="title")
624
  with gr.Row():
625
- with gr.Column(scale=2):
626
  chatbot = gr.Chatbot(elem_classes="gradio-output")
627
- language_select = gr.Dropdown(choices= language_option, elem_classes="gradio-input", label= "请选择要使用的语言")
628
- model_select = gr.Dropdown(choices=model_option, elem_classes="gradio-input",label="请选择要使用的大模型")
629
- input_box = gr.Textbox(label="输入", elem_classes="gradio-input", placeholder="请输入要判断的新闻", lines=3)
 
 
 
 
 
630
 
631
- with gr.Column(scale=1):
632
  img_input = gr.Image(label="上传图像", type="numpy")
633
  img_output = gr.Image(label="处理后的图像", type="numpy", visible=False)
634
- img_info = gr.Textbox(label="提取到的信息",lines=5,elem_classes="gradio-output")
635
- ans_box = gr.Textbox(label="gpt-4o", lines=5, elem_classes="gradio-output",visible=False)
 
636
  dialogue_box = gr.Textbox(label="React", lines=5, elem_classes="gradio-output", visible=False)
637
- clear = gr.Button("清空页面", elem_classes="gradio-button")
638
- submit_btn = gr.Button("提交", elem_classes="gradio-button")
 
 
 
 
 
 
 
 
 
639
  language_select.change(SelectLanguage, language_select)
640
  model_select.change(SelectModel, model_select)
641
 
 
642
  def user(user_input, history):
643
  if history is None:
644
  history = []
645
- return "", history + [[user_input, None]]
 
646
 
647
  def bot(history, rag_box):
648
  if history is None or len(history) == 0:
@@ -654,18 +709,20 @@ with gr.Blocks(css=css1) as demo:
654
  time.sleep(0.01)
655
  yield history
656
 
 
657
  submit_btn.click(img_size, img_input, img_output
 
 
658
  ).then(
659
- generate_img_summaries,img_output ,img_info
660
- ).then(
661
- start, [input_box,img_info], dialogue_box
662
  ).then(
663
  user, [input_box, chatbot], [input_box, chatbot]
664
  ).then(
665
  bot, [chatbot, dialogue_box], chatbot
666
  )
667
 
668
- clear.click(lambda: (None, None, None), inputs=None, outputs=[chatbot, ans_box, dialogue_box])
 
669
 
670
  if __name__ == "__main__":
671
- demo.launch()
 
26
  os.environ["REPLICATE_API_TOKEN"] = "r8_IYJpjwjrxegcUfBeBbyUxErJXXsnHDM4AlSQQ"
27
  os.environ["OPENAI_API_KEY"] = "sb-6a683cb3bd63a9b72040aa2dd08feff8b68f08a0e1d959f5"
28
  os.environ['OPENAI_BASE_URL'] = "https://api.openai-sb.com/v1/"
29
+ os.environ["SERPAPI_API_KEY"] = "dcc98b22d5f7d413979a175ff7d75b721c5992a3ee1e2363020b2bbdf4f82404" # you
30
  # os.environ['TAVILY_API_KEY'] = "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" #you
31
+ os.environ['TAVILY_API_KEY'] = "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" # zeng
32
+ # image_path = "C:/Users/Lenovo/Desktop/demo-repository-master/image/img_2.png"
33
  model = ChatOpenAI(model_name="gpt-4", temperature=0.6)
34
 
35
+
36
  def search_baidu(query) -> str:
37
  params = {
38
  "engine": "baidu_news",
 
51
  ])
52
  return final_output
53
 
54
+
55
  def search_bing(query) -> str:
56
  params = {
57
  "engine": "bing_news",
 
70
  ])
71
  return final_output
72
 
73
+
74
  def img_size(image):
75
  # img = Image.open(image)
76
  img = Image.fromarray(image.astype("uint8"))
 
84
  # resized_img.save(image_path)
85
  return resized_img
86
 
87
+
88
+ def search_image(query) -> str:
89
  params = {
90
+ "engine": "google_images",
91
+ "q": query,
92
+ "gl": "cn",
93
  }
94
  search = GoogleSearch(params)
95
  results = search.get_dict()
96
  thumbnails = [search['thumbnail'] for search in results['suggested_searches']][:3]
97
+ information = ""
98
  client = OpenAI()
99
  for idx, thumbnail in enumerate(thumbnails):
100
+ response = client.chat.completions.create(
101
+ model="gpt-4o-mini",
102
+ messages=[
103
+ {
104
+ "role": "user",
105
+ "content": [
106
+ {"type": "text", "text": "What’s in this image?Give a brief answer"},
107
+ {
108
+ "type": "image_url",
109
+ "image_url": {
110
+ "url": thumbnail,
111
+ },
112
+ },
113
+ ],
114
+ }
115
  ],
116
+ max_tokens=100,
117
+ )
118
+ response_content = response.choices[0].message.content
119
+ information = information + str(idx + 1) + ": " + response_content + "\n"
 
 
120
  return (information)
121
 
122
+
123
  search_baidu = Tool(
124
  name="Baidu News Search", # 工具名称
125
  func=search_baidu, # 引用search函数
 
137
  func=search_image, # 引用search函数
138
  description="搜索图片引擎,当你需要检索相关图片的时候调用,输入是检索query,输出是与query有关的图片的信息" # 工具描述
139
  )
140
+
141
+
142
  class ReplicateModel:
143
  def __init__(self, model_name: str):
144
  self.model_name = model_name
 
151
  )
152
  return output
153
 
154
+
155
  class DialogueAgent:
156
  def __init__(
157
  self,
 
187
  """
188
  self.message_history.append(f"{name}: {message}")
189
 
190
+
191
  class Replicate_DialogueAgent:
192
  def __init__(
193
  self,
 
227
  Concatenates {message} spoken by {name} into message history
228
  """
229
  self.message_history.append(f"{name}: {message}")
230
+
231
+
232
  class DialogueSimulator:
233
  def __init__(
234
  self,
 
270
 
271
  return speaker.name, message
272
 
273
+
274
  class Replicate_DialogueSimulator:
275
  def __init__(
276
  self,
 
312
 
313
  return speaker.name, message
314
 
315
+
316
  class DialogueAgentWithTools(DialogueAgent):
317
  def __init__(self, name: str, system_message: SystemMessage, model: ChatOpenAI, tools: List[BaseTool]):
318
  super().__init__(name, system_message, model)
 
326
  verbose=True,
327
  memory=ConversationBufferMemory(memory_key="chat_history", return_messages=True),
328
  )
329
+ message_input = "\n".join([self.system_message.content] + self.message_history + [self.prefix])
330
+ response = agent_chain.invoke({"input": message_input}, handle_parsing_errors=True)
331
+
332
+ # response = agent_chain.invoke(
333
+ # {"input": "\n".join([self.system_message.content] + self.message_history + [self.prefix],handle_parsing_errors=True)}
334
+ # )
335
  return response
336
 
337
+
338
  class Repliacte_DialogueAgentWithTools(Replicate_DialogueAgent):
339
+ def __init__(self, name: str, system_message: SystemMessage, replicate_model: ReplicateModel,
340
+ tools: List[BaseTool]):
341
  super().__init__(name, system_message, None) # 不再使用 ChatOpenAI 模型
342
  self.replicate_model = replicate_model # 存储 Replicate 模型
343
  self.tools = tools # 手动传递工具
 
351
  response = self.replicate_model.predict(input_data)
352
  return response
353
 
354
+
355
  ddg_search = DuckDuckGoSearchResults()
356
  arxiv_query = ArxivQueryRun()
357
  tavily_tool = TavilySearchResults(max_result=2)
358
 
359
  tools = [tavily_tool, search_baidu]
360
 
361
+
362
  def select_next_speaker(step: int, agents: List[DialogueAgent]) -> int:
363
  idx = step % len(agents)
364
  return idx
 
388
  agent_description = ChatOpenAI(temperature=1.0)(agent_specifier_prompt).content
389
  return agent_description
390
 
391
+
392
+ def generate_system_message_ch(name, description, tools, topic, img_information):
393
  return f"""Here is the topic of discussion: {topic}
394
  Your name is {name}.
395
 
 
440
  Stop speaking the moment you finish your evaluation.
441
  """
442
 
443
+
444
+ def generate_system_message_en(name, description, tools, topic, img_information):
445
  return f"""Here is the topic of discussion: {topic}
446
  Your name is {name}.
447
 
 
491
 
492
  Stop speaking the moment you finish your evaluation.
493
  """
494
+
495
+
496
  def encode_image(image):
497
  image = Image.fromarray(image.astype("uint8"))
498
  buffered = io.BytesIO()
 
501
  # with open(image_path, "rb") as image_file:
502
  # return base64.b64encode(image_file.read()).decode("utf-8")
503
 
504
+
505
  def image_summarize(img_base64, prompt):
506
  chat = ChatOpenAI(model="gpt-4o", max_tokens=256)
507
  msg = chat.invoke(
 
519
  )
520
  return msg.content
521
 
522
+
523
  def generate_img_summaries(image):
524
  # img_size(path)
525
  image_summaries = []
 
530
  image_summaries.append(image_summarize(base64_image, prompt))
531
  return image_summaries
532
 
533
+
534
  selected_language = "ch"
535
  selected_model = "gpt"
536
+
537
+
538
  def SelectLanguage(option):
539
  global selected_language
540
  if option == "英文":
541
  selected_language = "en"
542
  else:
543
  selected_language = "ch"
544
+
545
+
546
+ language_option = ["中文", "英文"]
547
+
548
 
549
  def SelectModel(option):
550
  global selected_model
 
556
  selected_model = "llama3-8b"
557
  else:
558
  selected_model = "mistral"
559
+
560
+
561
+ model_option = ["gpt-4o", "llama3-70b", "llama3-8b", "mistral"]
562
+
563
 
564
  def start(topic, image_summaries):
565
  max_iters = 3
 
573
  conversation_description = f"""Here is the news of conversation: {topic}
574
  The participants are: {', '.join(names.keys())}"""
575
 
576
+ agent_descriptions = {name: generate_agent_description(name, conversation_description, word_limit) for name in
577
+ names}
578
  if selected_language == "ch":
579
  agent_system_messages = {
580
  name: generate_system_message_ch(name, description, tools, topic, image_summaries)
 
616
  simulator.inject("Moderator", specified_topic)
617
  while n < max_iters:
618
  name, message = simulator.step()
619
+ result = result + "(" + name + "): " + message['output'] + "\n"
620
  # print(f"({name}): {message['output']}")
621
  # print("\n")
622
  n += 1
 
653
  return result
654
 
655
 
656
+ # start("9月18日,Trump 在纽约举行第二次暗杀未遂事件后首场竞选集会,现场共有1.8万名支持者参加。", "gpt") #topic是新闻,model_select是要选择的模型(gpt,llama3-70b,llama3-8b,mistral)
657
+
658
  title = "# 虚假信息检测"
659
 
660
  with gr.Blocks(css=css1) as demo:
661
  gr.Markdown(title, elem_id="title")
662
  with gr.Row():
663
+ with gr.Column(scale=4):
664
  chatbot = gr.Chatbot(elem_classes="gradio-output")
665
+ # with gr.Row():
666
+ # with gr.Column(scale=1):
667
+ # language_select = gr.Dropdown(choices=language_option, elem_classes="gradio-input",
668
+ # label="请选择要使用的语言")
669
+ # with gr.Column(scale=1):
670
+ # model_select = gr.Dropdown(choices=model_option, elem_classes="gradio-input", label="请选择要使用的大模型")
671
+ # input_box = gr.Textbox(label="输入", elem_classes="gradio-input", placeholder="请输入要判断的新闻", lines=3)
672
+ img_info = gr.Textbox(label="提取到的信息", lines=5, elem_classes="gradio-output")
673
 
674
+ with gr.Column(scale=2):
675
  img_input = gr.Image(label="上传图像", type="numpy")
676
  img_output = gr.Image(label="处理后的图像", type="numpy", visible=False)
677
+ input_box = gr.Textbox(label="输入", elem_classes="gradio-input", placeholder="请输入要判断的新闻", lines=3)
678
+ # img_info = gr.Textbox(label="提取到的信息", lines=5, elem_classes="gradio-output")
679
+ ans_box = gr.Textbox(label="gpt-4o", lines=5, elem_classes="gradio-output", visible=False)
680
  dialogue_box = gr.Textbox(label="React", lines=5, elem_classes="gradio-output", visible=False)
681
+ with gr.Row():
682
+ # with gr.Column(scale=1):
683
+ language_select = gr.Dropdown(choices=language_option, elem_classes="gradio-input",
684
+ label="请选择要使用的语言",scale=1)
685
+ # with gr.Column(scale=1):
686
+ model_select = gr.Dropdown(choices=model_option, elem_classes="gradio-input", label="请选择要使用的大模型",scale=1)
687
+ with gr.Row():
688
+ # with gr.Column(scale=1):
689
+ clear = gr.Button("清空页面", elem_classes="gradio-button", scale=1)
690
+ # with gr.Column(scale=1):
691
+ submit_btn = gr.Button("提交", elem_classes="gradio-button", scale=1)
692
  language_select.change(SelectLanguage, language_select)
693
  model_select.change(SelectModel, model_select)
694
 
695
+
696
  def user(user_input, history):
697
  if history is None:
698
  history = []
699
+ return user_input, history + [[user_input, None]]
700
+
701
 
702
  def bot(history, rag_box):
703
  if history is None or len(history) == 0:
 
709
  time.sleep(0.01)
710
  yield history
711
 
712
+
713
  submit_btn.click(img_size, img_input, img_output
714
+ ).then(
715
+ generate_img_summaries, img_output, img_info
716
  ).then(
717
+ start, [input_box, img_info], dialogue_box
 
 
718
  ).then(
719
  user, [input_box, chatbot], [input_box, chatbot]
720
  ).then(
721
  bot, [chatbot, dialogue_box], chatbot
722
  )
723
 
724
+ clear.click(lambda: (None, None, None, None, None, None), inputs=None,
725
+ outputs=[chatbot, ans_box, dialogue_box, img_input, img_info, img_output])
726
 
727
  if __name__ == "__main__":
728
+ demo.launch()