import PyPDF2
import openai
import json
import time

# OpenAI API anahtarınızı burada yerleştirin
openai.api_key = '<TRUFFLEHOG_REDACTED_OPENAI>'

def read_pdf(file_path):
    with open(file_path, "rb") as file:
        reader = PyPDF2.PdfReader(file)
        text = []
        for page in reader.pages:
            text.append(page.extract_text())
    return text

def process_with_gpt(text, model="gpt-3.5-turbo"):
    # The detailed prompt for data preparation
    prompt = (
        "I am developing an AI lifestyle medicine coach for my mobile app. The target users are individuals seeking "
        "lifestyle improvements, preventative health, and wellness solutions, as well as those looking to consult a "
        "health and wellness coach.\n\n"
        
        "The AI coach must behave similarly to a human health professional who has educated themselves in lifestyle "
        "medicine, following the guidelines, principles, and knowledge from books, publications, and resources. This AI "
        "coach should have extended knowledge and act according to the evidence-based approach of lifestyle medicine, "
        "which is why I am preparing a dataset from these resources.\n\n"
        
        "Since I am not a technical person or developer, I will need your guidance to ensure the data preparation and AI "
        "training process goes smoothly, especially when creating files like JSON.\n\n"
        
        "Here is my data preparation pipeline for training the AI:\n"
        "1. **Data Preparation Format**: I clean the text from books and publications, divide it into parts (such as "
        "chapters or sections), and format it for AI training.\n"
        "2. **AI Text Conversion**: I provide you with the cleaned text in parts, and I need you to convert it into a "
        "format suitable for AI training.\n"
        "3. **Sample Prompts and Guiding Questions**: After all the data is prepared for the chapter, I will ask you to "
        "generate more sample prompts for AI training and create more simplified guiding questions.\n"
        "4. **Final Step**: After all the data is prepared and extended, I will need your help to create JSON files for "
        "each part of the chapters to feed into the AI system, ensuring no critical information is lost.\n\n"
        
        "Here is the data preparation format I use:\n\n"
        
        "---\n\n"
        "**Data Preparation Format:**\n"
        "- **Title:** (Title of the book or publication)\n"
        "- **Chapter #:** (Name of chapter; if this is an article or publication without chapters, remove this)\n"
        "- **Part:** (Name of the part)\n"
        "- **Summary:** A short paragraph summary of the part\n"
        "- **Summary of the Content:** Main theme and key concepts\n"
        "- **Main Theme:** Explanation of the main theme of the part in sentence format\n"
        "- **Key Concepts:**\n"
        "   - A bullet point breakdown of the key concepts of the part\n"
        "- **Key Concepts Breakdown:**\n"
        "   - **Concept #:** Title\n"
        "   - **Definition**\n"
        "   - **Example**\n"
        "- **Key Learning Objectives:** (In bullet points)\n"
        "- **Sample Prompts for AI Training:** Scenario-based questions and expected AI responses\n"
        "- **Simplified Guiding Questions for AI:** (In bullet points)\n\n"
        
        "---\n\n"
        
        "Here's the text to be processed:\n\n"
        f"{text}"
    )
    
    response = openai.ChatCompletion.create(
        model=model,
        messages=[
            {"role": "system", "content": "You are an assistant that helps breaking down text into sections and analysis."},
            {"role": "user", "content": prompt}
        ],
        max_tokens=400
    )
    return response.choices[0].message['content'].strip()

def process_book(file_path):
    pages = read_pdf(file_path)
    results = []

    for i, page_text in enumerate(pages):
        try:
            print(f"Processing page {i+1}/{len(pages)}")
            result = process_with_gpt(page_text)
            results.append(result)
            time.sleep(20)  # Her çağrıdan sonra 20 saniyelik bekleme süresi
        except openai.error.RateLimitError:
            print("Rate limit exceeded. Waiting for 60 seconds before retrying.")
            time.sleep(60)
            result = process_with_gpt(page_text)  # Hata aldığında tekrar deneme
            results.append(result)
    return results

def save_results(results):
    for i, content in enumerate(results):
        output_file = f'page_{i+1}_analysis.json'
        with open(output_file, 'w', encoding='utf-8') as file:
            json.dump({"content": content}, file, ensure_ascii=False, indent=4)

def main():
    file_path = 'sample.pdf'
    results = process_book(file_path)
    save_results(results)

if __name__ == "__main__":
    main()

bu kodda yapılan işlemi anla ve hataları varsa düzelt. şu an bu program için rate limit error hatası yiyorum. lütfen kodda yapılanları bana açıkla ki doğru yanlış olanları gözlemleyebileyim