generator_utils.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
  3. import os
  4. import re
  5. from transformers import AutoTokenizer
  6. from octoai.client import Client
  7. import asyncio
  8. import magic
  9. from PyPDF2 import PdfReader
  10. import json
  11. from doc_processor import split_text_into_chunks
  12. import logging
  13. # Initialize logging
  14. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  15. def read_text_file(file_path):
  16. try:
  17. with open(file_path, 'r') as f:
  18. return f.read().strip() + ' '
  19. except Exception as e:
  20. logging.error(f"Error reading text file {file_path}: {e}")
  21. return ''
  22. def read_pdf_file(file_path):
  23. try:
  24. with open(file_path, 'rb') as f:
  25. pdf_reader = PdfReader(f)
  26. num_pages = len(pdf_reader.pages)
  27. file_text = [pdf_reader.pages[page_num].extract_text().strip() + ' ' for page_num in range(num_pages)]
  28. return ''.join(file_text)
  29. except Exception as e:
  30. logging.error(f"Error reading PDF file {file_path}: {e}")
  31. return ''
  32. def process_file(file_path):
  33. file_type = magic.from_file(file_path, mime=True)
  34. if file_type in ['text/plain', 'text/markdown']:
  35. return read_text_file(file_path)
  36. elif file_type == 'application/pdf':
  37. return read_pdf_file(file_path)
  38. else:
  39. logging.warning(f"Unsupported file type {file_type} for file {file_path}")
  40. return ''
  41. def read_file_content(context):
  42. file_strings = []
  43. for root, _, files in os.walk(context['data_dir']):
  44. for file in files:
  45. file_path = os.path.join(root, file)
  46. file_text = process_file(file_path)
  47. if file_text:
  48. file_strings.append(file_text)
  49. return ' '.join(file_strings)
  50. def parse_qa_to_json(response_string):
  51. # Adjusted regex to capture question-answer pairs more flexibly
  52. # This pattern accounts for optional numbering and different question/answer lead-ins
  53. pattern = re.compile(
  54. r"\d*\.\s*Question:\s*(.*?)\nAnswer:\s*(.*?)(?=\n\d*\.\s*Question:|\Z)",
  55. re.DOTALL
  56. )
  57. # Find all matches in the response string
  58. matches = pattern.findall(response_string)
  59. # Convert matches to a structured format
  60. qa_list = [{"question": match[0].strip(), "answer": match[1].strip()} for match in matches]
  61. # Convert the list to a JSON string
  62. return json.dumps(qa_list, indent=4)
  63. async def prepare_and_send_request(chat_service, api_context: dict, document_content: str, total_questions: int) -> dict:
  64. prompt_for_system = api_context['question_prompt_template'].format(total_questions=total_questions, language=api_context["language"])
  65. chat_request_payload = [{'role': 'system', 'content': prompt_for_system}, {'role': 'user', 'content': document_content}]
  66. return json.loads(await chat_service.execute_chat_request_async(api_context, chat_request_payload))
  67. async def generate_question_batches(chat_service, api_context: dict):
  68. document_text = read_file_content(api_context)
  69. tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf", pad_token="</s>", padding_side="right")
  70. document_batches = split_text_into_chunks(api_context, document_text, tokenizer)
  71. total_questions = api_context["total_questions"]
  72. batches_count = len(document_batches)
  73. base_questions_per_batch = total_questions // batches_count
  74. extra_questions = total_questions % batches_count
  75. print(f"Questions per batch: {base_questions_per_batch} (+1 for the first {extra_questions} batches), Total questions: {total_questions}, Batches: {batches_count}")
  76. generation_tasks = []
  77. for batch_index, batch_content in enumerate(document_batches):
  78. print(f"len of batch_content: {len(batch_content)}, batch_index: {batch_index}")
  79. #Distribute extra questions across the first few batches
  80. questions_in_current_batch = base_questions_per_batch + (1 if batch_index < extra_questions else 0)
  81. print(f"Batch {batch_index + 1} - {questions_in_current_batch} questions ********")
  82. generation_tasks.append(prepare_and_send_request(chat_service, api_context, batch_content, questions_in_current_batch))
  83. question_generation_results = await asyncio.gather(*generation_tasks)
  84. return question_generation_results