generator_utils.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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 openai
  5. import asyncio
  6. import magic
  7. from PyPDF2 import PdfReader
  8. from functools import partial
  9. import json
  10. from doc_processor import split_text_into_chunks
  11. import logging
  12. # Initialize logging
  13. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  14. # Manage rate limits with throttling
  15. rate_limit_threshold = 2000
  16. allowed_concurrent_requests = int(rate_limit_threshold * 0.75)
  17. request_limiter = asyncio.Semaphore(allowed_concurrent_requests)
  18. def read_text_file(file_path):
  19. try:
  20. with open(file_path, 'r') as f:
  21. return f.read().strip() + ' '
  22. except Exception as e:
  23. logging.error(f"Error reading text file {file_path}: {e}")
  24. return ''
  25. def read_pdf_file(file_path):
  26. try:
  27. with open(file_path, 'rb') as f:
  28. pdf_reader = PdfReader(f)
  29. num_pages = len(pdf_reader.pages)
  30. file_text = [pdf_reader.pages[page_num].extract_text().strip() + ' ' for page_num in range(num_pages)]
  31. return ''.join(file_text)
  32. except Exception as e:
  33. logging.error(f"Error reading PDF file {file_path}: {e}")
  34. return ''
  35. def process_file(file_path):
  36. file_type = magic.from_file(file_path, mime=True)
  37. if file_type in ['text/plain', 'text/markdown']:
  38. return read_text_file(file_path)
  39. elif file_type == 'application/pdf':
  40. return read_pdf_file(file_path)
  41. else:
  42. logging.warning(f"Unsupported file type {file_type} for file {file_path}")
  43. return ''
  44. def read_file_content(context):
  45. file_strings = []
  46. for root, _, files in os.walk(context['data_dir']):
  47. for file in files:
  48. file_path = os.path.join(root, file)
  49. file_text = process_file(file_path)
  50. if file_text:
  51. file_strings.append(file_text)
  52. return ' '.join(file_strings)
  53. async def execute_chat_request_async(api_context: dict, chat_request):
  54. async with request_limiter:
  55. try:
  56. event_loop = asyncio.get_running_loop()
  57. # Prepare the OpenAI API call
  58. openai_chat_call = partial(
  59. openai.ChatCompletion.create,
  60. model=api_context['model'],
  61. messages=chat_request,
  62. temperature=0.0
  63. )
  64. # Execute the API call in a separate thread
  65. response = await event_loop.run_in_executor(None, openai_chat_call)
  66. # Extract and return the assistant's response
  67. return next((message['message']['content'] for message in response.choices if message['message']['role'] == 'assistant'), "")
  68. except Exception as error:
  69. print(f"Error during chat request execution: {error}")
  70. return ""
  71. async def prepare_and_send_request(api_context: dict, document_content: str, total_questions: int) -> dict:
  72. prompt_for_system = api_context['question_prompt_template'].format(total_questions=total_questions, language=api_context["language"])
  73. chat_request_payload = [{'role': 'system', 'content': prompt_for_system}, {'role': 'user', 'content': document_content}]
  74. return json.loads(await execute_chat_request_async(api_context, chat_request_payload))
  75. async def generate_question_batches(api_context: dict):
  76. document_text = read_file_content(api_context)
  77. document_batches = split_text_into_chunks(api_context, document_text)
  78. total_questions = api_context["total_questions"]
  79. batches_count = len(document_batches)
  80. base_questions_per_batch = total_questions // batches_count
  81. extra_questions = total_questions % batches_count
  82. print(f"Questions per batch: {base_questions_per_batch} (+1 for the first {extra_questions} batches), Total questions: {total_questions}, Batches: {batches_count}")
  83. generation_tasks = []
  84. for batch_index, batch_content in enumerate(document_batches):
  85. # Distribute extra questions across the first few batches
  86. questions_in_current_batch = base_questions_per_batch + (1 if batch_index < extra_questions else 0)
  87. print(f"Batch {batch_index + 1} - {questions_in_current_batch} questions ********")
  88. generation_tasks.append(prepare_and_send_request(api_context, batch_content, questions_in_current_batch))
  89. question_generation_results = await asyncio.gather(*generation_tasks)
  90. return question_generation_results