Untitled
unknown
plain_text
a year ago
4.6 kB
16
Indexable
import time
import os
import signal
from openpyxl import load_workbook
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from langchain_openai import ChatOpenAI
from langchain.schema import SystemMessage, HumanMessage
import constants
import win32com.client as win32
import pythoncom
import os, shutil
from config import excel_file
os.environ["OPENAI_API_KEY"] = constants.APIKEY
# # Delete the cache file that breaks the script
# folder_path = r"C:\Users\XXXXX\AppData\Local\Temp\gen_py\3.10\00020813-0000-0000-C000-000000000046x0x1x9"
# if os.path.exists(folder_path): shutil.rmtree(folder_path)
def check_question_clarity(question):
chat_model = ChatOpenAI(model="gpt-4o-mini", temperature=0)
messages = [
SystemMessage(content="You provide clarity score for question. Give score from 1 to 10. "
"1 = very unclear. 10 = very clear."),
HumanMessage(
content=f"Evaluate how clear is the question:\n"
f"{question}\n"
f"Provide only the score. If score is lower than 9 then add a suggestion to improve clarity score."
)
]
res = chat_model.invoke(messages)
output = res.content
return output
class ExcelEventHandler(FileSystemEventHandler):
def __init__(self, file_path):
self.file_path = file_path
self.observer = Observer()
self.last_modified_time = 0
self.is_writing = False
def on_modified(self, event):
if event.src_path == self.file_path and not self.is_writing:
current_time = time.time()
if current_time - self.last_modified_time > 2: # Add a delay to avoid immediate re-trigger
self.last_modified_time = current_time
print("File saved. Running function...")
self.process_file()
def process_file(self):
try:
# Initialize the COM library
pythoncom.CoInitialize()
# Determine the active sheet name using pywin32
excel = win32.gencache.EnsureDispatch('Excel.Application')
workbook = excel.Workbooks.Open(self.file_path)
sheet_name = workbook.ActiveSheet.Name
workbook.Close(SaveChanges=False)
excel.Quit()
# Run the function to write to the Excel file
self.is_writing = True
write_to_excel(self.file_path, sheet_name)
self.is_writing = False
# Open the Excel file
os.startfile(self.file_path)
print("File reopened.")
except Exception as e:
print(f"Error: {e}")
finally:
# Uninitialize the COM library
pythoncom.CoUninitialize()
def start(self):
self.observer.schedule(self, os.path.dirname(self.file_path), recursive=False)
self.observer.start()
print("Watching for file changes...")
def stop(self):
self.observer.stop()
self.observer.join()
def write_to_excel(file_path, sheet_name):
try:
# Load the workbook
wb = load_workbook(filename=file_path)
# Select the sheet
sheet = wb[sheet_name]
# Iterate through rows starting from the third row
for row in sheet.iter_rows(min_row=3, max_col=3):
question = row[0].value
clarity_score = row[2].value # Change to the third column
if question and not clarity_score:
# Check question clarity and write the score to the third column
score = check_question_clarity(question)
row_idx = row[0].row # Get the row index
sheet.cell(row=row_idx, column=3).value = score # Change to the third column
print(f"Updated clarity score for question: {question}")
# Save the workbook
wb.save(file_path)
print("Successfully updated clarity scores in the Excel file.")
except Exception as e:
print(f"Error: {e}")
def signal_handler(sig, frame):
print('You pressed Ctrl+C! Exiting.')
exit(0)
if __name__ == "__main__":
# Register the signal handler for Ctrl+C
signal.signal(signal.SIGINT, signal_handler)
event_handler = ExcelEventHandler(excel_file)
event_handler.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
event_handler.stop()
event_handler.stop()Editor is loading...
Leave a Comment