generator_utils.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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. from functools import partial
  11. import json
  12. from doc_processor import split_text_into_chunks
  13. import logging
  14. # Initialize logging
  15. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  16. # Manage rate limits with throttling
  17. rate_limit_threshold = 2000
  18. allowed_concurrent_requests = int(rate_limit_threshold * 0.75)
  19. request_limiter = asyncio.Semaphore(allowed_concurrent_requests)
  20. def read_text_file(file_path):
  21. try:
  22. with open(file_path, 'r') as f:
  23. return f.read().strip() + ' '
  24. except Exception as e:
  25. logging.error(f"Error reading text file {file_path}: {e}")
  26. return ''
  27. def read_pdf_file(file_path):
  28. try:
  29. with open(file_path, 'rb') as f:
  30. pdf_reader = PdfReader(f)
  31. num_pages = len(pdf_reader.pages)
  32. file_text = [pdf_reader.pages[page_num].extract_text().strip() + ' ' for page_num in range(num_pages)]
  33. return ''.join(file_text)
  34. except Exception as e:
  35. logging.error(f"Error reading PDF file {file_path}: {e}")
  36. return ''
  37. def process_file(file_path):
  38. file_type = magic.from_file(file_path, mime=True)
  39. if file_type in ['text/plain', 'text/markdown']:
  40. return read_text_file(file_path)
  41. elif file_type == 'application/pdf':
  42. return read_pdf_file(file_path)
  43. else:
  44. logging.warning(f"Unsupported file type {file_type} for file {file_path}")
  45. return ''
  46. def read_file_content(context):
  47. file_strings = []
  48. for root, _, files in os.walk(context['data_dir']):
  49. for file in files:
  50. file_path = os.path.join(root, file)
  51. file_text = process_file(file_path)
  52. if file_text:
  53. file_strings.append(file_text)
  54. return ' '.join(file_strings)
  55. def parse_qa_to_json(response_string):
  56. # Adjusted regex to capture question-answer pairs more flexibly
  57. # This pattern accounts for optional numbering and different question/answer lead-ins
  58. pattern = re.compile(
  59. r"\d*\.\s*Question:\s*(.*?)\nAnswer:\s*(.*?)(?=\n\d*\.\s*Question:|\Z)",
  60. re.DOTALL
  61. )
  62. # Find all matches in the response string
  63. matches = pattern.findall(response_string)
  64. # Convert matches to a structured format
  65. qa_list = [{"question": match[0].strip(), "answer": match[1].strip()} for match in matches]
  66. # Convert the list to a JSON string
  67. return json.dumps(qa_list, indent=4)
  68. async def execute_chat_request_async(api_context: dict, chat_request):
  69. async with request_limiter:
  70. try:
  71. event_loop = asyncio.get_running_loop()
  72. # Prepare the API call
  73. client = Client(api_context['api_key'])
  74. api_chat_call = partial(
  75. client.chat.completions.create,
  76. model=api_context['model'],
  77. messages=chat_request,
  78. temperature=0.0
  79. )
  80. # Execute the API call in a separate thread
  81. response = await event_loop.run_in_executor(None, api_chat_call)
  82. # Extract and return the assistant's response
  83. # return next((message['message']['content'] for message in response.choices if message['message']['role'] == 'assistant'), "")
  84. assistant_response = next((choice.message.content for choice in response.choices if choice.message.role == 'assistant'), "")
  85. assistant_response_json = parse_qa_to_json(assistant_response)
  86. return assistant_response_json
  87. except Exception as error:
  88. print(f"Error during chat request execution: {error}")
  89. return ""
  90. async def prepare_and_send_request(api_context: dict, document_content: str, total_questions: int) -> dict:
  91. prompt_for_system = api_context['question_prompt_template'].format(total_questions=total_questions, language=api_context["language"])
  92. chat_request_payload = [{'role': 'system', 'content': prompt_for_system}, {'role': 'user', 'content': document_content}]
  93. return json.loads(await execute_chat_request_async(api_context, chat_request_payload))
  94. async def generate_question_batches(api_context: dict):
  95. document_text = read_file_content(api_context)
  96. tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf", pad_token="</s>", padding_side="right")
  97. document_batches = split_text_into_chunks(api_context, document_text, tokenizer)
  98. total_questions = api_context["total_questions"]
  99. batches_count = len(document_batches)
  100. base_questions_per_batch = total_questions // batches_count
  101. extra_questions = total_questions % batches_count
  102. print(f"Questions per batch: {base_questions_per_batch} (+1 for the first {extra_questions} batches), Total questions: {total_questions}, Batches: {batches_count}")
  103. generation_tasks = []
  104. for batch_index, batch_content in enumerate(document_batches):
  105. print(f"len of batch_content: {len(batch_content)}, batch_index: {batch_index}")
  106. #Distribute extra questions across the first few batches
  107. questions_in_current_batch = base_questions_per_batch + (1 if batch_index < extra_questions else 0)
  108. print(f"Batch {batch_index + 1} - {questions_in_current_batch} questions ********")
  109. generation_tasks.append(prepare_and_send_request(api_context, batch_content, questions_in_current_batch))
  110. # generation_tasks.append(prepare_and_send_request(api_context, document_batches_2[0], total_questions))
  111. question_generation_results = await asyncio.gather(*generation_tasks)
  112. return question_generation_results