Guest User

API KEY Chatgpt - Corecteaza limba engleza text from docx files.py

a guest
Oct 17th, 2024
305
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.02 KB | None | 0 0
  1. import os
  2. from openai import OpenAI
  3. from dotenv import load_dotenv
  4. import logging
  5. from docx import Document
  6.  
  7.  
  8. # Set up logging
  9. logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
  10.  
  11. # Load environment variables from the .env file
  12. load_dotenv()
  13.  
  14. # Initialize the OpenAI client
  15. api_key = os.getenv('OPENAI_API_KEY')
  16. if not api_key:
  17.     api_key = "YOUR-API-KEY"
  18.     logging.warning("Using hardcoded API key. It's recommended to use environment variables for security.")
  19.  
  20. client = OpenAI(api_key=api_key)
  21.  
  22. def correct_text(text):
  23.     prompt = f"""
  24.    You are an expert in English language correction. Please follow these instructions strictly:
  25.  
  26.    1. Main task:
  27.    - Correct spelling, punctuation, and obvious grammatical errors.
  28.    - Improve awkward or incorrect expressions.
  29.    - DO NOT alter the basic structure of sentences or change the core meaning.
  30.  
  31.    2. What to correct:
  32.    - Misspelled words
  33.    - Incorrect punctuation
  34.    - Clear grammatical errors (e.g., subject-verb agreement, tense issues)
  35.    - Awkward or incorrect expressions
  36.    - Improve word choice where necessary, but maintain the original meaning
  37.  
  38.    3. What NOT to correct:
  39.    - Do not change the overall structure of paragraphs or sentences
  40.    - Do not add or remove information
  41.    - Do not alter quotes or dialogues
  42.    - Do not change words or expressions in languages other than English
  43.    - Do not modify technical terms or proper nouns you're unsure about
  44.  
  45.    4. Maintaining structure:
  46.    - Keep the same paragraph structure
  47.    - Preserve original formatting and spacing as much as possible
  48.  
  49.    5. Conservation:
  50.    - If you're not absolutely certain something is an error, leave it unchanged
  51.  
  52.    6. Response:
  53.    - Return the corrected text without any additional explanations or comments
  54.  
  55.    Here's the text for correction:
  56.    {text}
  57.    """
  58.  
  59.     try:
  60.         response = client.chat.completions.create(
  61.             model="gpt-4",
  62.             messages=[
  63.                 {"role": "system", "content": "You are an expert in English language correction."},
  64.                 {"role": "user", "content": prompt}
  65.             ]
  66.         )
  67.         corrected_text = response.choices[0].message.content.strip()
  68.         logging.debug("Successfully received response from OpenAI API")
  69.         return corrected_text
  70.     except Exception as e:
  71.         logging.error(f"Error calling OpenAI API: {e}")
  72.         return text  # Return original text if there's an error
  73.  
  74. def process_docx_file(input_file, output_file):
  75.     logging.info(f"Processing file: {input_file}")
  76.  
  77.     try:
  78.         doc = Document(input_file)
  79.         corrected_doc = Document()
  80.  
  81.         for paragraph in doc.paragraphs:
  82.             corrected_text = correct_text(paragraph.text)
  83.             new_paragraph = corrected_doc.add_paragraph()
  84.             new_paragraph.text = corrected_text
  85.             new_paragraph.style = paragraph.style
  86.  
  87.         for table in doc.tables:
  88.             new_table = corrected_doc.add_table(rows=len(table.rows), cols=len(table.columns))
  89.             for i, row in enumerate(table.rows):
  90.                 for j, cell in enumerate(row.cells):
  91.                     corrected_text = correct_text(cell.text)
  92.                     new_table.cell(i, j).text = corrected_text
  93.  
  94.         corrected_doc.save(output_file)
  95.         logging.info(f"Successfully wrote corrected content to {output_file}")
  96.     except Exception as e:
  97.         logging.error(f"Error processing file '{input_file}': {e}")
  98.  
  99. def process_all_files():
  100.     input_dir = r"D:\4"
  101.     output_dir = r"D:\4\Output"
  102.  
  103.     if not os.path.exists(output_dir):
  104.         os.makedirs(output_dir)
  105.  
  106.     for filename in os.listdir(input_dir):
  107.         if filename.endswith(".docx"):
  108.             input_path = os.path.join(input_dir, filename)
  109.             output_path = os.path.join(output_dir, filename)
  110.             process_docx_file(input_path, output_path)
  111.  
  112. if __name__ == "__main__":
  113.     process_all_files()
  114.     logging.info("Script execution completed")
Advertisement
Add Comment
Please, Sign In to add comment