DocUA commited on
Commit
c136365
·
1 Parent(s): c3ea8ac

Without AI (local files)

Browse files
Files changed (1) hide show
  1. main.py +123 -91
main.py CHANGED
@@ -41,17 +41,27 @@ from dotenv import load_dotenv
41
  load_dotenv()
42
 
43
  # OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
44
- OPENAI_API_KEY = "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"
45
 
46
- os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
47
-
48
- embed_model = OpenAIEmbedding(model_name="text-embedding-3-small")
49
- Settings.embed_model = embed_model
50
  Settings.context_window = 20000
51
  Settings.chunk_size = 2048
52
  Settings.similarity_top_k = 20
53
 
54
 
 
 
 
 
 
 
 
 
 
 
 
55
  # Параметри S3
56
  BUCKET_NAME = "legal-position"
57
  PREFIX_RETRIEVER = "Save_Index/" # Префікс для всього вмісту, який потрібно завантажити
@@ -74,32 +84,32 @@ s3_client = boto3.client(
74
  # region_name="eu-north-1"
75
  # )
76
 
77
- # Створюємо локальну директорію, якщо вона не існує
78
- LOCAL_DIR.mkdir(parents=True, exist_ok=True)
79
-
80
- # Функція для завантаження файлу з S3
81
- def download_s3_file(bucket_name, s3_key, local_path):
82
- s3_client.download_file(bucket_name, s3_key, str(local_path))
83
- print(f"Завантажено: {s3_key} -> {local_path}")
84
-
85
- # Функція для завантаження всієї папки з S3 у локальну директорію
86
- def download_s3_folder(bucket_name, prefix, local_dir):
87
- response = s3_client.list_objects_v2(Bucket=bucket_name, Prefix=prefix)
88
- if 'Contents' in response:
89
- for obj in response['Contents']:
90
- s3_key = obj['Key']
91
- # Пропускаємо "папку" (кореневий префікс) у S3
92
- if s3_key.endswith('/'):
93
- continue
94
- # Визначаємо локальний шлях, де буде збережений файл
95
- local_file_path = local_dir / Path(s3_key).relative_to(prefix)
96
- local_file_path.parent.mkdir(parents=True, exist_ok=True) # створення підкаталогів, якщо потрібно
97
- # Завантажуємо файл
98
- s3_client.download_file(bucket_name, s3_key, str(local_file_path))
99
- print(f"Завантажено: {s3_key} -> {local_file_path}")
100
-
101
- # Завантаження всього вмісту папки `Save_Index` з S3 у локальну директорію `Save_Index_Local`
102
- download_s3_folder(BUCKET_NAME, PREFIX_RETRIEVER, LOCAL_DIR)
103
 
104
 
105
 
@@ -342,55 +352,71 @@ def create_gradio_interface():
342
 
343
  with gr.Row():
344
  url_input = gr.Textbox(label="URL судового рішення:")
345
- question_input = gr.Textbox(label="Ваше питання:")
346
 
347
  with gr.Row():
348
- generate_position_button = gr.Button("Генерувати короткий зміст позиції суду")
349
- search_with_ai_button = gr.Button("Пошук із ШІ", interactive=False)
350
- search_without_ai_button = gr.Button("Пошук без ШІ")
351
- analyze_button = gr.Button("Аналіз", interactive=False)
 
352
 
353
- position_output = gr.Markdown(label="Короткий зміст позиції суду за введеним рішенням")
354
- search_output = gr.Markdown(label="Результат пошуку")
355
- analysis_output = gr.Markdown(label="Результат аналізу")
356
 
357
  # Два об'єкти стану для зберігання legal_position_json та nodes
358
  state_lp_json = gr.State()
359
  state_nodes = gr.State()
360
 
361
- async def generate_position_action(url):
362
- try:
363
- court_decision_text = extract_court_decision_text(url)
364
- legal_position_json = generate_legal_position(court_decision_text, "")
365
- position_output_content = f"**Короткий зміст позиції суду за введеним рішенням:**\n *{legal_position_json['title']}*: \n{legal_position_json['text']} **Категорія:** \n{legal_position_json['category']} ({legal_position_json['proceeding']})\n\n"
366
- return position_output_content, legal_position_json
367
- except Exception as e:
368
- return f"Error during position generation: {str(e)}", None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
369
 
370
- async def search_with_ai_action(legal_position_json):
371
  try:
372
- query_text = legal_position_json["title"] + ': ' + legal_position_json["text"] + ': ' + legal_position_json["proceeding"] + ': ' + legal_position_json["category"]
373
- nodes = await retriever_bm25.aretrieve(query_text)
374
 
375
- sources_output = "\n **Результати пошуку (наявні правові позиції ВСУ):** \n\n"
376
  for index, node in enumerate(nodes, start=1):
377
- source_title = node.node.metadata.get('title')
378
  doc_ids = node.node.metadata.get('doc_id')
379
- lp_ids = node.node.metadata.get('lp_id')
380
  links = get_links_html(doc_ids)
381
- links_lp = get_links_html_lp(lp_ids)
382
- sources_output += f"\n[{index}] *{source_title}* {links_lp} 👉 Score: {node.score} {links}\n"
383
 
384
- return sources_output, nodes
385
  except Exception as e:
386
  return f"Error during search: {str(e)}", None
387
 
388
- async def search_without_ai_action(url):
389
  try:
390
- court_decision_text = extract_court_decision_text(url)
391
- nodes = await retriever_bm25.aretrieve(court_decision_text)
392
 
393
- search_output_content = f"**Результати пошуку (наявні правові позиції ВСУ):** \n\n"
394
  for index, node in enumerate(nodes, start=1):
395
  source_title = node.node.metadata.get('title', 'Невідомий заголовок')
396
  doc_ids = node.node.metadata.get('doc_id')
@@ -456,44 +482,50 @@ def create_gradio_interface():
456
  return f"Error during analysis: {str(e)}"
457
 
458
  # Підключаємо функції до кнопок з оновленими входами та виходами
459
- generate_position_button.click(
460
- fn=generate_position_action,
461
- inputs=url_input,
462
- outputs=[position_output, state_lp_json]
463
- )
464
- generate_position_button.click(
465
- fn=lambda: gr.update(interactive=True),
466
- inputs=None,
467
- outputs=search_with_ai_button
468
- )
469
-
470
- search_with_ai_button.click(
471
- fn=search_with_ai_action,
472
- inputs=state_lp_json,
473
- outputs=[search_output, state_nodes]
474
- )
475
- search_with_ai_button.click(
476
- fn=lambda: gr.update(interactive=True),
477
- inputs=None,
478
- outputs=analyze_button
479
- )
480
 
481
  search_without_ai_button.click(
482
  fn=search_without_ai_action,
483
  inputs=url_input,
484
- outputs=[search_output, state_nodes]
485
  )
486
- search_without_ai_button.click(
487
- fn=lambda: gr.update(interactive=True),
488
- inputs=None,
489
- outputs=analyze_button
 
 
 
 
 
 
490
  )
491
 
492
- analyze_button.click(
493
- fn=analyze_action,
494
- inputs=[state_lp_json, question_input, state_nodes],
495
- outputs=analysis_output
496
- )
497
 
498
  return app
499
 
 
41
  load_dotenv()
42
 
43
  # OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
 
44
 
45
+ # os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
46
+ #
47
+ # embed_model = OpenAIEmbedding(model_name="text-embedding-3-small")
48
+ # Settings.embed_model = embed_model
49
  Settings.context_window = 20000
50
  Settings.chunk_size = 2048
51
  Settings.similarity_top_k = 20
52
 
53
 
54
+ # Параметри для локального імпорту
55
+ LOCAL_DIR = Path("/home/Legal_Position/Save_index") # Локальна директорія для збереження даних з Save_Index
56
+
57
+ # Ініціалізація локального завантаження без S3
58
+ def load_local_folder(local_dir):
59
+ for file_path in local_dir.glob('**/*'):
60
+ if file_path.is_file():
61
+ print(f"Завантажено локальний файл: {file_path}")
62
+
63
+ load_local_folder(LOCAL_DIR)
64
+
65
  # Параметри S3
66
  BUCKET_NAME = "legal-position"
67
  PREFIX_RETRIEVER = "Save_Index/" # Префікс для всього вмісту, який потрібно завантажити
 
84
  # region_name="eu-north-1"
85
  # )
86
 
87
+ # # Створюємо локальну директорію, якщо вона не існує
88
+ # LOCAL_DIR.mkdir(parents=True, exist_ok=True)
89
+ #
90
+ # # Функція для завантаження файлу з S3
91
+ # def download_s3_file(bucket_name, s3_key, local_path):
92
+ # s3_client.download_file(bucket_name, s3_key, str(local_path))
93
+ # print(f"Завантажено: {s3_key} -> {local_path}")
94
+ #
95
+ # # Функція для завантаження всієї папки з S3 у локальну директорію
96
+ # def download_s3_folder(bucket_name, prefix, local_dir):
97
+ # response = s3_client.list_objects_v2(Bucket=bucket_name, Prefix=prefix)
98
+ # if 'Contents' in response:
99
+ # for obj in response['Contents']:
100
+ # s3_key = obj['Key']
101
+ # # Пропускаємо "папку" (кореневий префікс) у S3
102
+ # if s3_key.endswith('/'):
103
+ # continue
104
+ # # Визначаємо локальний шлях, де буде збережений файл
105
+ # local_file_path = local_dir / Path(s3_key).relative_to(prefix)
106
+ # local_file_path.parent.mkdir(parents=True, exist_ok=True) # створення підкаталогів, якщо потрібно
107
+ # # Завантажуємо файл
108
+ # s3_client.download_file(bucket_name, s3_key, str(local_file_path))
109
+ # print(f"Завантажено: {s3_key} -> {local_file_path}")
110
+ #
111
+ # # Завантаження всього вмісту папки `Save_Index` з S3 у локальну директорію `Save_Index_Local`
112
+ # download_s3_folder(BUCKET_NAME, PREFIX_RETRIEVER, LOCAL_DIR)
113
 
114
 
115
 
 
352
 
353
  with gr.Row():
354
  url_input = gr.Textbox(label="URL судового рішення:")
355
+ question_input = gr.Textbox(label="Текстовий запит:")
356
 
357
  with gr.Row():
358
+ # generate_position_button = gr.Button("Генерувати короткий зміст позиції суду")
359
+ # search_with_ai_button = gr.Button("Пошук із ШІ", interactive=False)
360
+ search_without_ai_button = gr.Button("Пошук за посиланням")
361
+ search_without_ai_button_query = gr.Button("Пошук за текстовим запитом")
362
+ # analyze_button = gr.Button("Аналіз", interactive=False)
363
 
364
+ # position_output = gr.Markdown(label="Короткий зміст позиції суду за введеним рішенням")
365
+ search_output_link = gr.Markdown(label="Результат пошуку за посиланням")
366
+ search_output_text = gr.Markdown(label="Результат пошуку за текстовим запитом")
367
 
368
  # Два об'єкти стану для зберігання legal_position_json та nodes
369
  state_lp_json = gr.State()
370
  state_nodes = gr.State()
371
 
372
+ # async def generate_position_action(url):
373
+ # try:
374
+ # court_decision_text = extract_court_decision_text(url)
375
+ # legal_position_json = generate_legal_position(court_decision_text, "")
376
+ # position_output_content = f"**Короткий зміст позиції суду за введеним рішенням:**\n *{legal_position_json['title']}*: \n{legal_position_json['text']} **Категорія:** \n{legal_position_json['category']} ({legal_position_json['proceeding']})\n\n"
377
+ # return position_output_content, legal_position_json
378
+ # except Exception as e:
379
+ # return f"Error during position generation: {str(e)}", None
380
+
381
+ # async def search_with_ai_action(legal_position_json):
382
+ # try:
383
+ # query_text = legal_position_json["title"] + ': ' + legal_position_json["text"] + ': ' + legal_position_json["proceeding"] + ': ' + legal_position_json["category"]
384
+ # nodes = await retriever_bm25.aretrieve(query_text)
385
+ #
386
+ # sources_output = "\n **Результати пошуку (наявні правові позиції ВСУ):** \n\n"
387
+ # for index, node in enumerate(nodes, start=1):
388
+ # source_title = node.node.metadata.get('title')
389
+ # doc_ids = node.node.metadata.get('doc_id')
390
+ # lp_ids = node.node.metadata.get('lp_id')
391
+ # links = get_links_html(doc_ids)
392
+ # links_lp = get_links_html_lp(lp_ids)
393
+ # sources_output += f"\n[{index}] *{source_title}* {links_lp} 👉 Score: {node.score} {links}\n"
394
+ #
395
+ # return sources_output, nodes
396
+ # except Exception as e:
397
+ # return f"Error during search: {str(e)}", None
398
 
399
+ async def search_without_ai_action(url):
400
  try:
401
+ court_decision_text = extract_court_decision_text(url)
402
+ nodes = await retriever_bm25.aretrieve(court_decision_text)
403
 
404
+ search_output_content = f"**Результати пошуку (наявні правові позиції ВС) за посиланням:** \n\n"
405
  for index, node in enumerate(nodes, start=1):
406
+ source_title = node.node.metadata.get('title', 'Невідомий заголовок')
407
  doc_ids = node.node.metadata.get('doc_id')
 
408
  links = get_links_html(doc_ids)
409
+ search_output_content += f"\n[{index}] *{source_title}* 👉 Score: {node.score} {links}\n"
 
410
 
411
+ return search_output_content, nodes
412
  except Exception as e:
413
  return f"Error during search: {str(e)}", None
414
 
415
+ async def search_without_ai_action_text(question_input):
416
  try:
417
+ nodes = await retriever_bm25.aretrieve(question_input)
 
418
 
419
+ search_output_content = f"**Результати пошуку (наявні правові позиції ВС) за текстовим запитом:** \n\n"
420
  for index, node in enumerate(nodes, start=1):
421
  source_title = node.node.metadata.get('title', 'Невідомий заголовок')
422
  doc_ids = node.node.metadata.get('doc_id')
 
482
  return f"Error during analysis: {str(e)}"
483
 
484
  # Підключаємо функції до кнопок з оновленими входами та виходами
485
+ # generate_position_button.click(
486
+ # fn=generate_position_action,
487
+ # inputs=url_input,
488
+ # outputs=[position_output, state_lp_json]
489
+ # )
490
+ # generate_position_button.click(
491
+ # fn=lambda: gr.update(interactive=True),
492
+ # inputs=None,
493
+ # outputs=search_with_ai_button
494
+ # )
495
+
496
+ # search_with_ai_button.click(
497
+ # fn=search_with_ai_action,
498
+ # inputs=state_lp_json,
499
+ # outputs=[search_output, state_nodes]
500
+ # )
501
+ # search_with_ai_button.click(
502
+ # fn=lambda: gr.update(interactive=True),
503
+ # inputs=None,
504
+ # outputs=analyze_button
505
+ # )
506
 
507
  search_without_ai_button.click(
508
  fn=search_without_ai_action,
509
  inputs=url_input,
510
+ outputs=[search_output_link, state_nodes]
511
  )
512
+ # search_without_ai_button.click(
513
+ # fn=lambda: gr.update(interactive=True),
514
+ # inputs=None,
515
+ # outputs=analyze_button
516
+ # )
517
+
518
+ search_without_ai_button_query.click(
519
+ fn=search_without_ai_action_text,
520
+ inputs=question_input,
521
+ outputs=[search_output_text, state_nodes]
522
  )
523
 
524
+ # analyze_button.click(
525
+ # fn=analyze_action,
526
+ # inputs=[state_lp_json, question_input, state_nodes],
527
+ # outputs=analysis_output
528
+ # )
529
 
530
  return app
531