Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- from openai import OpenAI
- from dotenv import load_dotenv
- import logging
- from docx import Document
- # Set up logging
- logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
- # Load environment variables from the .env file
- load_dotenv()
- # Initialize the OpenAI client
- api_key = os.getenv('OPENAI_API_KEY')
- if not api_key:
- api_key = "YOUR-API-KEY"
- logging.warning("Using hardcoded API key. It's recommended to use environment variables for security.")
- client = OpenAI(api_key=api_key)
- def correct_text(text):
- prompt = f"""
- You are an expert in English language correction. Please follow these instructions strictly:
- 1. Main task:
- - Correct spelling, punctuation, and obvious grammatical errors.
- - Improve awkward or incorrect expressions.
- - DO NOT alter the basic structure of sentences or change the core meaning.
- 2. What to correct:
- - Misspelled words
- - Incorrect punctuation
- - Clear grammatical errors (e.g., subject-verb agreement, tense issues)
- - Awkward or incorrect expressions
- - Improve word choice where necessary, but maintain the original meaning
- 3. What NOT to correct:
- - Do not change the overall structure of paragraphs or sentences
- - Do not add or remove information
- - Do not alter quotes or dialogues
- - Do not change words or expressions in languages other than English
- - Do not modify technical terms or proper nouns you're unsure about
- 4. Maintaining structure:
- - Keep the same paragraph structure
- - Preserve original formatting and spacing as much as possible
- 5. Conservation:
- - If you're not absolutely certain something is an error, leave it unchanged
- 6. Response:
- - Return the corrected text without any additional explanations or comments
- Here's the text for correction:
- {text}
- """
- try:
- response = client.chat.completions.create(
- model="gpt-4",
- messages=[
- {"role": "system", "content": "You are an expert in English language correction."},
- {"role": "user", "content": prompt}
- ]
- )
- corrected_text = response.choices[0].message.content.strip()
- logging.debug("Successfully received response from OpenAI API")
- return corrected_text
- except Exception as e:
- logging.error(f"Error calling OpenAI API: {e}")
- return text # Return original text if there's an error
- def process_docx_file(input_file, output_file):
- logging.info(f"Processing file: {input_file}")
- try:
- doc = Document(input_file)
- corrected_doc = Document()
- for paragraph in doc.paragraphs:
- corrected_text = correct_text(paragraph.text)
- new_paragraph = corrected_doc.add_paragraph()
- new_paragraph.text = corrected_text
- new_paragraph.style = paragraph.style
- for table in doc.tables:
- new_table = corrected_doc.add_table(rows=len(table.rows), cols=len(table.columns))
- for i, row in enumerate(table.rows):
- for j, cell in enumerate(row.cells):
- corrected_text = correct_text(cell.text)
- new_table.cell(i, j).text = corrected_text
- corrected_doc.save(output_file)
- logging.info(f"Successfully wrote corrected content to {output_file}")
- except Exception as e:
- logging.error(f"Error processing file '{input_file}': {e}")
- def process_all_files():
- input_dir = r"D:\4"
- output_dir = r"D:\4\Output"
- if not os.path.exists(output_dir):
- os.makedirs(output_dir)
- for filename in os.listdir(input_dir):
- if filename.endswith(".docx"):
- input_path = os.path.join(input_dir, filename)
- output_path = os.path.join(output_dir, filename)
- process_docx_file(input_path, output_path)
- if __name__ == "__main__":
- process_all_files()
- logging.info("Script execution completed")
Advertisement
Add Comment
Please, Sign In to add comment