class CustomCTkButton(ctk.CTkButton):
def destroy(self):
try:
super().destroy()
except AttributeError as e:
if "_font" in str(e):
# Handle the specific error by setting a default font
self._font = None
super().destroy()
else:
raise e
Now use CustomCTkButton instead of CTkButton in your application
Main function to create the root window and start the application
from three_screens.middleman import create_first_screen
create_first_screen(root)
root.mainloop()
logging.info("Application closed successfully")
print(Fore.BLUE + "Application closed successfully")
except Exception as e:
logging.error(f"Error in main function: {e}")
print(Fore.YELLOW + f"Error in main function: {e}")
if name == "main":
main()
Assistant
Nod.
User
import customtkinter as ctk
import logging
from colorama import Fore
from middleman import create_second_screen
from main import CustomCTkButton # Import the custom button class
button = CustomCTkButton(frame, text="Next", command=lambda: move_to_second_screen(frame))
button.place(relx=0.5, rely=0.5, anchor='center')
logging.info("First screen created successfully")
print(Fore.BLUE + "First screen created successfully")
except Exception as e:
logging.error(f"Error creating first screen: {e}")
print(Fore.YELLOW + f"Error creating first screen: {e}")
Function to move to the second screen
def move_to_second_screen(current_frame):
try:
current_frame.pack_forget()
create_second_screen(current_frame.master)
logging.info("Moved to second screen successfully")
print(Fore.GREEN + "Moved to second screen successfully")
except Exception as e:
logging.error(f"Error moving to second screen: {e}")
print(Fore.ORANGE + f"Error moving to second screen: {e}")
Assistant
Nod.
User
parser.py
import re
from PyPDF2 import PdfReader # Ensure you have PyPDF2 installed
from analyzation.gpt_instance import gpt_instance
def extract_text_from_pdf(pdf_path):
pages_text = []
with open(pdf_path, 'rb') as file:
reader = PdfReader(file)
for page in reader.pages:
pages_text.append(page.extract_text())
return pages_text
def find_abstract_page(pages_text):
for i, page in enumerate(pages_text):
# Check for "Abstract" or "Abstrak" in the page text
if re.search(r"\b(?:Abstract|Abstrak)\b", page, re.IGNORECASE):
return i, page # Return the page index and the page content
return None, None # If no abstract found
start_point = "You are a paper abstract extractor. You will meet paper from different languages, prioritize Indonesian output. Your job is to analyze text snippet you receive and extract abstract out of it."
go_point = abstract_page_content
if abstract_page_content:
print(f"Found Abstract on Page {abstract_page_index + 1}")
code
# Step 3: Pass the entire page content to GPT instance function
gpt_response = gpt_instance(start_point, go_point)
# Step 4: Print the extraction result
print( termcolor.colored( f"ABSTRACT:\n\n{gpt_response}", "light_magenta" ) )
else:
print("[Paper contain no abstract]")
Assistant
Nod.
User
scraper.py
from selenium import webdriver
from selenium_stealth import stealth
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selectolax.lexbor import LexborHTMLParser
from google_scholar_py import CustomGoogleScholarOrganic
from proxy_handler import setup_proxy
from rate_limit_manager import call_with_rate_limit
from proxy_rotation_manager import proxy_generator
import time
import random
from termcolor import colored
from typing import List, Dict
from middleman import create_third_screen
create_third_screen(current_frame.master)
logging.info("Moved to third screen successfully")
print(Fore.GREEN + "Moved to third screen successfully")
except Exception as e:
logging.error(f"Error moving to third screen: {e}")
print(Fore.ORANGE + f"Error moving to third screen: {e}")
Assistant
Nod.
User
import customtkinter as ctk
import logging
from PIL import Image, ImageTk
from colorama import Fore
from main import CustomCTkButton # Import the custom button class
Default pseudo passage
pseudo_passage = """
Hasil analisa menunjukkan keselarasan antara penggunaan sitasi penulis dan data yang dijelaskan di dalam makalah. Analisa menunjukkan bahwa sebagian besar sitasi digunakan dengan benar, walaupun terdapat ketidakselarasan pada beberapa bagian. Beberapa sitasi mengenai kondisi psikologi individu di Kota Jombang tidak memiliki koneksi pada topik fenomena burnout yang sedang dibahas sekarang.
Verifikasi Kutipan:
• Referensi 1: Keberadaan data dikonfirmasi. Kutipan relevan. Nilai kebenaran: 95%.
• Referensi 2: Data terdapat di abstrak sitasi. Sedikit salah representasi. Nilai kebenaran: 85%.
• Referensi 3: Sitasi tidak ber-konteks tepat pada topik. Nilai kebenaran: 65%.
• Referensi 4: Data sebagian ada. Konteks tidak sepenuhnya selaras. Nilai kebenaran: 70%.
• Referensi 5: Representasi data akurat. Namun tidak terintegrasi baik. Nilai kebenaran: 82%
Analisis Maksud Penulis:
Maksud penulis dalam menggunakan kutipan ini tampaknya adalah untuk memperkuat argumen utama dengan sumber yang kredibel dan relevan. Sebagian besar kutipan digunakan dengan akurat, meskipun ada beberapa ketidaksesuaian konteks pada beberapa bagian. Secara keseluruhan, referensi-referensi tersebut secara signifikan mendukung klaim penelitian, menunjukkan dasar penelitian yang baik dan terinformasi. Hal ini mengindikasikan pendekatan yang sengaja dan hati-hati dalam penggunaan kutipan oleh penulis.
"""
so well, there is one button in first screen (created by first_screen.py). i think this screen meant to accept pdf file, because it is meant to do that. so hey, i need event handler so that enable the button to accept pdf file. then i need it to play second screen, then also print notif on terminal that pdf is accepted and print filename of the pdf. lets add testchecker func on top of first_screen.py to test that. also, add loggingsto the func and use termcolor. lets do it extreme simple.
Assistant
Sure! Below is a modified version of the create_first_screen function in first_screen.py, including an event handler for the button that allows the user to select a PDF file and logs the actions, while also using termcolor for terminal notifications.
python
import customtkinter as ctk
import logging
from colorama import Fore
from tkinter import filedialog
from middleman import create_second_screen
from main import CustomCTkButton # Import the custom button class
# Function to test if the selected file is a PDF
def testchecker(file_path):
if file_path.endswith('.pdf'):
logging.info(f"PDF accepted: {file_path}")
print(Fore.GREEN + f"PDF accepted: {file_path}")
return True
else:
logging.warning(f"Invalid file format: {file_path}")
print(Fore.RED + f"Invalid file format: {file_path}")
return False
# Function to create the first screen
def create_first_screen(root):
try:
frame = ctk.CTkFrame(root)
frame.pack(expand=True, fill='both')
def open_file():
file_path = filedialog.askopenfilename(filetypes=[("PDF files", "*.pdf")])
if file_path and testchecker(file_path):
move_to_second_screen(frame)
button = CustomCTkButton(frame, text="Upload PDF", command=open_file)
button.place(relx=0.5, rely=0.5, anchor='center')
logging.info("First screen created successfully")
print(Fore.BLUE + "First screen created successfully")
except Exception as e:
logging.error(f"Error creating first screen: {e}")
print(Fore.YELLOW + f"Error creating first screen: {e}")
# Function to move to the second screen
def move_to_second_screen(current_frame):
try:
current_frame.pack_forget()
create_second_screen(current_frame.master)
logging.info("Moved to second screen successfully")
print(Fore.GREEN + "Moved to second screen successfully")
except Exception as e:
logging.error(f"Error moving to second screen: {e}")
print(Fore.ORANGE + f"Error moving to second screen: {e}")
User
dont use colorama, but termcolor lib
Assistant
Certainly! Below is the modified version of the create_first_screen function using the termcolor library instead of colorama for terminal notifications:
python
import customtkinter as ctk
import logging
from termcolor import colored
from tkinter import filedialog
from middleman import create_second_screen
from main import CustomCTkButton # Import the custom button class
# Function to test if the selected file is a PDF
def testchecker(file_path):
if file_path.endswith('.pdf'):
logging.info(f"PDF accepted: {file_path}")
print(colored(f"PDF accepted: {file_path}", 'green'))
return True
else:
logging.warning(f"Invalid file format: {file_path}")
print(colored(f"Invalid file format: {file_path}", 'red'))
return False
# Function to create the first screen
def create_first_screen(root):
try:
frame = ctk.CTkFrame(root)
frame.pack(expand=True, fill='both')
def open_file():
file_path = filedialog.askopenfilename(filetypes=[("PDF files", "*.pdf")])
if file_path and testchecker(file_path):
move_to_second_screen(frame)
button = CustomCTkButton(frame, text="Upload PDF", command=open_file)
button.place(relx=0.5, rely=0.5, anchor='center')
logging.info("First screen created successfully")
print(colored("First screen created successfully", 'blue'))
except Exception as e:
logging.error(f"Error creating first screen: {e}")
print(colored(f"Error creating first screen: {e}", 'yellow'))
# Function to move to the second screen
def move_to_second_screen(current_frame):
try:
current_frame.pack_forget()
create_second_screen(current_frame.master)
logging.info("Moved to second screen successfully")
print(colored("Moved to second screen successfully", 'green'))
except Exception as e:
logging.error(f"Error moving to second screen: {e}")
print(colored(f"Error moving to second screen: {e}", 'orange'))
Key Changes:
Termcolor Usage: Replaced the colorama print statements with termcolor.colored for colored terminal output.
PDF Validation and Notifications: Updated the notifications for accepted PDFs and invalid formats to use termcolor.
You can now substitute this create_first_screen function in your first_screen.py as needed.
User
one more. u notice lazy imports in screen scripts where i import script only when needed. dont change it. it is for preventing circular import. bringthe import back to its original place.
Assistant
Sure! Below is the modified version of the create_first_screen function with the imports moved back to their original place at the top of the script, while still retaining the lazy imports for specific functions where needed.
python
import customtkinter as ctk
import logging
from termcolor import colored
from tkinter import filedialog
from main import CustomCTkButton # Import the custom button class
# Function to test if the selected file is a PDF
def testchecker(file_path):
if file_path.endswith('.pdf'):
logging.info(f"PDF accepted: {file_path}")
print(colored(f"PDF accepted: {file_path}", 'green'))
return True
else:
logging.warning(f"Invalid file format: {file_path}")
print(colored(f"Invalid file format: {file_path}", 'red'))
return False
# Function to create the first screen
def create_first_screen(root):
try:
frame = ctk.CTkFrame(root)
frame.pack(expand=True, fill='both')
def open_file():
file_path = filedialog.askopenfilename(filetypes=[("PDF files", "*.pdf")])
if file_path and testchecker(file_path):
# Lazy import for circular import prevention
from middleman import create_second_screen
move_to_second_screen(frame)
button = CustomCTkButton(frame, text="Upload PDF", command=open_file)
button.place(relx=0.5, rely=0.5, anchor='center')
logging.info("First screen created successfully")
print(colored("First screen created successfully", 'blue'))
except Exception as e:
logging.error(f"Error creating first screen: {e}")
print(colored(f"Error creating first screen: {e}", 'yellow'))
# Function to move to the second screen
def move_to_second_screen(current_frame):
try:
current_frame.pack_forget()
# Lazy import for circular import prevention
from middleman import create_second_screen
create_second_screen(current_frame.master)
logging.info("Moved to second screen successfully")
print(colored("Moved to second screen successfully", 'green'))
except Exception as e:
logging.error(f"Error moving to second screen: {e}")
print(colored(f"Error moving to second screen: {e}", 'orange'))
User
also theres typo error with lazy import. make sure to use from three_screens.middleman instead of from middleman in future.
Assistant
Sure! I'll correct the lazy imports to include the full path from three_screens.middleman as per your requirement. Below is the updated code with the corrected lazy import:
python
import customtkinter as ctk
import logging
from termcolor import colored
from tkinter import filedialog
from main import CustomCTkButton # Import the custom button class
# Function to test if the selected file is a PDF
def testchecker(file_path):
if file_path.endswith('.pdf'):
logging.info(f"PDF accepted: {file_path}")
print(colored(f"PDF accepted: {file_path}", 'green'))
return True
else:
logging.warning(f"Invalid file format: {file_path}")
print(colored(f"Invalid file format: {file_path}", 'red'))
return False
# Function to create the first screen
def create_first_screen(root):
try:
frame = ctk.CTkFrame(root)
frame.pack(expand=True, fill='both')
def open_file():
file_path = filedialog.askopenfilename(filetypes=[("PDF files", "*.pdf")])
if file_path and testchecker(file_path):
# Lazy import for circular import prevention
from three_screens.middleman import create_second_screen
move_to_second_screen(frame)
button = CustomCTkButton(frame, text="Upload PDF", command=open_file)
button.place(relx=0.5, rely=0.5, anchor='center')
logging.info("First screen created successfully")
print(colored("First screen created successfully", 'blue'))
except Exception as e:
logging.error(f"Error creating first screen: {e}")
print(colored(f"Error creating first screen: {e}", 'yellow'))
# Function to move to the second screen
def move_to_second_screen(current_frame):
try:
current_frame.pack_forget()
# Lazy import for circular import prevention
from three_screens.middleman import create_second_screen
create_second_screen(current_frame.master)
logging.info("Moved to second screen successfully")
print(colored("Moved to second screen successfully", 'green'))
except Exception as e:
logging.error(f"Error moving to second screen: {e}")
print(colored(f"Error moving to second screen: {e}", 'orange'))
User
there was import error tracing from middleman. i fix middleman.py. here is the updated script:
middleman.py
from three_screens.second_screen import *
from three_screens.first_screen import *
from three_screens.third_screen import *
Assistant
Great! With your update to middleman.py, importing everything from all three screens as shown will allow you to access the functions defined in each screen directly.
Here’s how the updated middleman.py looks:
python
# middleman.py
from three_screens.second_screen import *
from three_screens.first_screen import *
from three_screens.third_screen import *
Implications:
Access to Functions: By using import *, you’ll be able to call any function from the second_screen, first_screen, and third_screen modules as if they were defined in middleman.py.
Namespace Management: While this type of import can simplify access to functions, it can also lead to potential naming conflicts if two modules define functions with the same name.
Clarity and Maintainability: Depending on your project's complexity, consider whether using import * may reduce readability for others reviewing the code. Importing functions explicitly may improve clarity about where each function originates.
Now that you have made the change in middleman.py, you can continue using the existing lazy imports in your other screen scripts without further issues. If everything is functioning as intended, you’re good to go! If you have more features or fixes in mind, let me know!
User
we have set firstscreen button to print filename of pdf. now, i need it to set second ctkinter screen that display the first 7 words in the pdf content. second screen, it mean it show up beside the original ctkinter screen. use testchecker for this code.
Assistant
To display the first 7 words from the content of the selected PDF on the second screen beside the original tkinter screen, you'll need to modify both the first_screen.py file to extract the text from the PDF and create a new function in the second_screen.py file to show this text.
Updates Needed:
First Screen (first_screen.py): Modify the open_file() function to extract the first 7 words from the selected PDF.
Second Screen (second_screen.py): Update the second screen to accept the extracted words and display them in a CTkTextbox.
Updated Code Snippets:
first_screen.py
Add the code to extract the first seven words of the PDF:
python
User
no no, what i mean by second screen is not second_screen.py. what i mean is external screen that show up outside of our original established three screens. u know for testing purpose.
Assistant
Got it! If you want to display the extracted text in an external tkinter window (a separate popup window) instead of modifying the existing second_screen.py, we can create a new function to handle this. The external window will show the first seven words from the PDF when the button is clicked.
Here's how you can adjust your first_screen.py to create an external window for displaying the PDF content:
Updated first_screen.py
Add a new function called create_external_window to show the first seven words in a separate window:
python
User
i need move_to_second_screen to still run. you know to keep theoriginal process.
Assistant
Understood! You want to maintain the original process flow of transitioning to the second screen while also displaying the extracted first seven words in an external window. Below is the adjusted code for first_screen.py that keeps the original behavior intact.
Updated first_screen.py
Now, the open_file() function will continue to call move_to_second_screen to navigate through the original screens while also calling the new function to display the first seven words in an external window.
Here's how you can implement this:
python
User
can u use customtkinter instead of old tkinter to create external popup window?
Assistant
Certainly! You can use customtkinter to create the external popup window instead of the standard tkinter. Below is the updated implementation for the create_external_window function that utilizes customtkinter to create the popup window.
Updated first_screen.py with customtkinter for the External Window
python
User
lets edit eventhandler for the button now. so, i have this script in parser.py in 'parser' folder. it contain a class named PDFAbstractExtractor that can detect where abstract is in given paper pdf and extract abstract from it. lets set firstscreen button so that it use this class to extract the pdf
Assistant
To modify the button's event handler in first_screen.py to use the PDFAbstractExtractor class from parser.py, you'll first need to ensure that the class is properly imported and utilized when a PDF file is selected.
Here’s how to implement the new functionality:
Import the PDFAbstractExtractor class at the top of first_screen.py.
Modify the open_file method to utilize this class for extracting the abstract from the selected PDF.
Assuming the PDFAbstractExtractor Class Structure
Before proceeding, make sure the PDFAbstractExtractor class in parser.py has the necessary methods to open a PDF and extract the abstract text. Here's an example of what that class might look like:
Example Structure of PDFAbstractExtractor
python
# parser.py
import re
from PyPDF2 import PdfReader # Ensure you have PyPDF2 installed
class PDFAbstractExtractor:
def __init__(self, pdf_path):
self.pdf_path = pdf_path
def extract_text_from_pdf(self):
pages_text = []
with open(self.pdf_path, 'rb') as file:
reader = PdfReader(file)
for page in reader.pages:
page_text = page.extract_text()
if page_text:
pages_text.append(page_text)
return pages_text
def find_abstract(self):
pages_text = self.extract_text_from_pdf()
for i, page in enumerate(pages_text):
# Check for "Abstract" or "Abstrak" in the page text
if re.search(r"\b(?:Abstract|Abstrak)\b", page, re.IGNORECASE):
return i, page # Return the page index and the page content
return None, None # If no abstract found
Modifications in first_screen.py
User
i havent give u the script. so, lets have the button to display the extracted abstract to our external window. u know, extracted abstract from the pdf. for your ref, here is parser.py script:
------------------------------
parser.py
import re
from PyPDF2 import PdfReader # Ensure you have PyPDF2 installed
from analyzation.gpt_instance import gpt_instance
import termcolor
def log(self, message, color):
"""Log messages with color."""
print(termcolor.colored(message, color))
def extract_text_from_pdf(self):
"""Extract text from each page of the PDF."""
self.log(f"Starting text extraction from {self.pdf_path}...", "cyan")
try:
with open(self.pdf_path, 'rb') as file:
reader = PdfReader(file)
self.pages_text = [page.extract_text() for page in reader.pages]
self.log(f"Extracted text from {len(self.pages_text)} pages.", "green")
except Exception as e:
self.log(f"Error extracting text from PDF: {str(e)}", "red")
def find_abstract_page(self):
"""Find the page containing the abstract."""
self.log("Searching for abstract page...", "cyan")
for i, page in enumerate(self.pages_text):
if re.search(r"\b(?:Abstract|Abstrak)\b", page, re.IGNORECASE):
self.abstract_page_index = i
self.abstract_page_content = page
self.log(f"Abstract found on page {self.abstract_page_index + 1}.", "green")
return
self.log("No abstract found in the document.", "yellow")
self.abstract_page_index = None
self.abstract_page_content = None
def extract_abstract(self):
"""Extract the abstract using GPT instance."""
if self.abstract_page_content:
start_point = "You are a paper abstract extractor. You will meet paper from different languages, prioritize Indonesian output. Your job is to analyze text snippet you receive and extract abstract out of it."
self.log("Passing the abstract content to GPT for extraction...", "cyan")
try:
gpt_response = gpt_instance(start_point, self.abstract_page_content)
# Print found abstract
print(termcolor.colored(f"PAGE:\n\n{self.abstract_page_content}", "yellow"))
self.log(f"Found Abstract on Page {self.abstract_page_index + 1}", "green")
print(termcolor.colored(f"ABSTRACT:\n\n{gpt_response}", "light_magenta"))
except Exception as e:
self.log(f"Error during GPT extraction: {str(e)}", "red")
else:
self.log("[Paper contains no abstract]", "yellow")
def process(self):
"""Process the PDF to extract the abstract."""
self.extract_text_from_pdf()
self.find_abstract_page()
self.extract_abstract()
Assistant
Thank you for sharing the PDFAbstractExtractor class from parser.py. Based on this script, we can refine the event handler in first_screen.py to use this class for extracting the abstract and displaying it in the external window.
Updated first_screen.py
Here’s how to implement the usage of PDFAbstractExtractor to process the PDF and display the extracted abstract in a custom tkinter window:
python
User
u havent set def open_file() block to adjust to the new change. it still expect testchecker(), and other errors.
Assistant
I apologize for the oversight. Let’s refine the open_file() function to correctly handle the extraction of the abstract using the PDFAbstractExtractor class while ensuring that testchecker() functionality is properly integrated.
Here’s the corrected version of the first_screen.py that eliminates the unnecessary checks and incorporates the PDFAbstractExtractor properly. The open_file() method should now use the extractor directly after checking that a PDF file is selected.
Updated first_screen.py
Here’s the revised code:
python
Not yet included in a published release.
def scrape_scholar_search_result(self) -> list[Dict, Dict]:
'''Scrapes Google Scholar results based on the search query.'''
print(colored(f"Starting to scrape Google Scholar for query: {self.search_query}", 'yellow'))
# Initialize the scraper
parser = CustomGoogleScholarOrganic()
# Use rate limiting to call the scraping function
try:
self.scholar_scrape_result = call_with_rate_limit(parser.scrape_google_scholar_organic_results,
query=self.search_query,
pagination=False,
save_to_csv=False,
save_to_json=False)
print(colored("Successfully scraped Google Scholar results.", 'green'))
except Exception as e:
print(colored(f"Error while scraping Google Scholar results: {e}", 'red'))
return self.scholar_scrape_result
def parse_abstract(self, parser_containing_link: LexborHTMLParser):
'''
This function parses the abstract from a given page and appends it to the results list.
'''
possible_tags = ['meta[name="description"]', 'div', 'p'] # Possible tags where abstracts may be found
abstract = None
try:
# Check for abstract in common tags
for tag in possible_tags:
if tag == 'meta[name="description"]':
meta_abstract = parser_containing_link.css_first(tag)
if meta_abstract:
abstract = meta_abstract.attrs['content']
print(colored("Abstract found in meta tag.", 'light_magenta'))
break
for element in parser_containing_link.css(tag):
if 'abstract' in element.attrs.get('class', []):
abstract = element.text()
print(colored("Abstract found in a <div> or <p> tag with 'abstract' class.", 'light_magenta'))
break
if abstract:
break
return abstract
except Exception as e:
print(colored(f"Error parsing abstract: {e}", 'red'))
return None
# Method to extract abstract from a url's content
def scrape_abstract(self, url: str) -> str:
'''
Extracts abstracts from the provided URL.
Arguments:
- url: URL to scrape abstracts from.
'''
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
# Chrome options for stealth
options.add_experimental_option('excludeSwitches', ['enable-automation', 'enable-logging'])
options.add_experimental_option('useAutomationExtension', False)
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=options)
stealth(driver,
languages=['en-US', 'en'],
vendor='Google Inc.',
platform='Win32',
webgl_vendor='Intel Inc.',
renderer='Intel Iris OpenGL Engine',
fix_hairline=True,
)
results_data = []
print(colored(f"Fetching URL: {url}...", 'yellow'))
driver.get(url)
time.sleep(random.randint(1, 3)) # Sleep to avoid getting blocked
parser = LexborHTMLParser(driver.page_source)
scraped_abstract = self.parse_abstract(parser_containing_link=parser)
driver.quit()
print(colored("Driver closed. Scraping completed.", 'green'))
return scraped_abstract
# Method to extract abstract from many urls content
def scrape_many_abstracts(self, urls:List) -> List:
abstracts = [self.scrape_abstract(url) for url in urls]
return abstracts
Example usage
if name == "main":
scraper = ScholarScraper(search_query="sadness psychology", max_results=5)
from middleman import create_first_screen
create_first_screen(current_frame.master)
logging.info("Moved to first screen successfully")
print(Fore.GREEN + "Moved to first screen successfully")
except Exception as e:
logging.error(f"Error moving to first screen: {e}")
print(Fore.ORANGE + f"Error moving to first screen: {e}")
Changes Made:
File Dialog: Added an open_file function that triggers a file dialog to select a PDF file.
PDF Validation: The testchecker function checks if the selected file has a .pdf extension. It logs the result and prints messages using termcolor.
Button Update: The button now calls open_file to handle PDF uploads.
You can replace the existing create_first_screen function in your first_screen.py with the modified version above. This simple implementation should achieve your requirements as specified.
Key Adjustments:
Imports: Moved the import statements for create_second_screen back to their original place, while keeping the lazy imports for circular import prevention within the relevant functions.
No Changes: Kept the logic and structure of the code the same as requested.
You can replace the existing function in your first_screen.py with the updated version above.
Key Adjustments:
Correct Lazy Imports: Changed the lazy imports to use from three_screens.middleman for both create_second_screen calls.
You can replace the previously provided function in your first_screen.py with this corrected version. If you need any further modifications, feel free to ask!
import customtkinter as ctk
import logging
from termcolor import colored
from tkinter import filedialog
from main import CustomCTkButton # Import the custom button class
from PyPDF2 import PdfReader # Make sure PyPDF2 is installed
def extract_first_seven_words(pdf_path):
"""Extracts the first 7 words from the PDF file."""
with open(pdf_path, 'rb') as file:
reader = PdfReader(file)
text = ''
for page in reader.pages:
text += page.extract_text() + ' '
# Return the first 7 words
return ' '.join(text.split()[:7])
# Function to test if the selected file is a PDF
def testchecker(file_path):
if file_path.endswith('.pdf'):
logging.info(f"PDF accepted: {file_path}")
print(colored(f"PDF accepted: {file_path}", 'green'))
return True
else:
logging.warning(f"Invalid file format: {file_path}")
print(colored(f"Invalid file format: {file_path}", 'red'))
return False
# Function to create the first screen
def create_first_screen(root):
try:
frame = ctk.CTkFrame(root)
frame.pack(expand=True, fill='both')
def open_file():
file_path = filedialog.askopenfilename(filetypes=[("PDF files", "*.pdf")])
if file_path and testchecker(file_path):
first_seven_words = extract_first_seven_words(file_path)
move_to_second_screen(frame, first_seven_words)
button = CustomCTkButton(frame, text="Upload PDF", command=open_file)
button.place(relx=0.5, rely=0.5, anchor='center')
logging.info("First screen created successfully")
print(colored("First screen created successfully", 'blue'))
except Exception as e:
logging.error(f"Error creating first screen: {e}")
print(colored(f"Error creating first screen: {e}", 'yellow'))
# Function to move to the second screen
def move_to_second_screen(current_frame, first_seven_words):
try:
current_frame.pack_forget()
from three_screens.middleman import create_second_screen
create_second_screen(current_frame.master, first_seven_words)
logging.info("Moved to second screen successfully")
print(colored("Moved to second screen successfully", 'green'))
except Exception as e:
logging.error(f"Error moving to second screen: {e}")
print(colored(f"Error moving to second screen: {e}", 'orange'))
second_screen.py
Update the second screen to display the first 7 words:
python
import customtkinter as ctk
import logging
from termcolor import colored
from main import CustomCTkButton # Import the custom button class
# Function to create the second screen
def create_second_screen(root, first_seven_words):
try:
frame = ctk.CTkFrame(root)
frame.pack(expand=True, fill='both')
# Create a label to display the first 7 words
words_label = ctk.CTkLabel(frame, text="First 7 Words from PDF:")
words_label.pack(pady=(20, 0))
words_display = ctk.CTkTextbox(frame, height=100, font=("Calibri Light", 16))
words_display.pack(expand=True, fill='both')
words_display.insert('1.0', first_seven_words) # Insert the first 7 words
logging.info("Second screen created successfully")
print(colored("Second screen created successfully", 'blue'))
except Exception as e:
logging.error(f"Error creating second screen: {e}")
print(colored(f"Error creating second screen: {e}", 'yellow'))
Summary of Changes:
PDF Extraction: The function extract_first_seven_words(pdf_path) is added to read the PDF and extract the first seven words.
Data Transfer: The move_to_second_screen function in first_screen.py now passes the extracted words to the second screen.
Display: In second_screen.py, a CTkTextbox displays the first seven words extracted from the PDF.
Now, when you run your application and upload a PDF file, the first seven words will show up on the second screen beside the original first screen. If you have any further changes or features you want to add, just let me know!
import customtkinter as ctk
import logging
from termcolor import colored
from tkinter import filedialog, Toplevel, Label
from main import CustomCTkButton # Import the custom button class
from PyPDF2 import PdfReader # Make sure PyPDF2 is installed
def extract_first_seven_words(pdf_path):
"""Extracts the first 7 words from the PDF file."""
with open(pdf_path, 'rb') as file:
reader = PdfReader(file)
text = ''
for page in reader.pages:
text += page.extract_text() + ' '
# Return the first 7 words
return ' '.join(text.split()[:7])
# Function to test if the selected file is a PDF
def testchecker(file_path):
if file_path.endswith('.pdf'):
logging.info(f"PDF accepted: {file_path}")
print(colored(f"PDF accepted: {file_path}", 'green'))
return True
else:
logging.warning(f"Invalid file format: {file_path}")
print(colored(f"Invalid file format: {file_path}", 'red'))
return False
def create_external_window(words):
"""Creates an external window to display the first seven words."""
external_window = Toplevel()
external_window.title("PDF Content")
external_window.geometry("400x200")
label = Label(external_window, text="First 7 Words from PDF:")
label.pack(pady=10)
words_label = Label(external_window, text=words, wraplength=350)
words_label.pack(pady=10)
external_window.mainloop()
# Function to create the first screen
def create_first_screen(root):
try:
frame = ctk.CTkFrame(root)
frame.pack(expand=True, fill='both')
def open_file():
file_path = filedialog.askopenfilename(filetypes=[("PDF files", "*.pdf")])
if file_path and testchecker(file_path):
first_seven_words = extract_first_seven_words(file_path)
# Show the first seven words in an external window
create_external_window(first_seven_words)
button = CustomCTkButton(frame, text="Upload PDF", command=open_file)
button.place(relx=0.5, rely=0.5, anchor='center')
logging.info("First screen created successfully")
print(colored("First screen created successfully", 'blue'))
except Exception as e:
logging.error(f"Error creating first screen: {e}")
print(colored(f"Error creating first screen: {e}", 'yellow'))
# Note: The change in move_to_second_screen has been removed as it's no longer needed.
Key Changes:
External Window Creation: The create_external_window function creates a new Toplevel window to display the first seven words from the PDF.
Window Management: This function is called immediately after extracting the words from the PDF when the file is selected.
With these changes, running your application and selecting a PDF file will display the first seven words in a new external window. The main application will remain unchanged, and this window will serve as a testing area for displaying the extracted text. If you have any more requests or adaptations to make, feel free to let me know!
import customtkinter as ctk
import logging
from termcolor import colored
from tkinter import filedialog, Toplevel, Label
from main import CustomCTkButton # Import the custom button class
from PyPDF2 import PdfReader # Make sure PyPDF2 is installed
def extract_first_seven_words(pdf_path):
"""Extracts the first 7 words from the PDF file."""
with open(pdf_path, 'rb') as file:
reader = PdfReader(file)
text = ''
for page in reader.pages:
text += page.extract_text() + ' '
# Return the first 7 words
return ' '.join(text.split()[:7])
# Function to test if the selected file is a PDF
def testchecker(file_path):
if file_path.endswith('.pdf'):
logging.info(f"PDF accepted: {file_path}")
print(colored(f"PDF accepted: {file_path}", 'green'))
return True
else:
logging.warning(f"Invalid file format: {file_path}")
print(colored(f"Invalid file format: {file_path}", 'red'))
return False
def create_external_window(words):
"""Creates an external window to display the first seven words."""
external_window = Toplevel()
external_window.title("PDF Content")
external_window.geometry("400x200")
label = Label(external_window, text="First 7 Words from PDF:")
label.pack(pady=10)
words_label = Label(external_window, text=words, wraplength=350)
words_label.pack(pady=10)
external_window.mainloop()
# Function to create the first screen
def create_first_screen(root):
try:
frame = ctk.CTkFrame(root)
frame.pack(expand=True, fill='both')
def open_file():
file_path = filedialog.askopenfilename(filetypes=[("PDF files", "*.pdf")])
if file_path and testchecker(file_path):
first_seven_words = extract_first_seven_words(file_path)
# Show the first seven words in an external window
create_external_window(first_seven_words)
# Also move to the second screen
move_to_second_screen(frame)
button = CustomCTkButton(frame, text="Upload PDF", command=open_file)
button.place(relx=0.5, rely=0.5, anchor='center')
logging.info("First screen created successfully")
print(colored("First screen created successfully", 'blue'))
except Exception as e:
logging.error(f"Error creating first screen: {e}")
print(colored(f"Error creating first screen: {e}", 'yellow'))
# Function to move to the second screen
def move_to_second_screen(current_frame):
try:
current_frame.pack_forget()
from three_screens.middleman import create_second_screen
create_second_screen(current_frame.master)
logging.info("Moved to second screen successfully")
print(colored("Moved to second screen successfully", 'green'))
except Exception as e:
logging.error(f"Error moving to second screen: {e}")
print(colored(f"Error moving to second screen: {e}", 'orange'))
Summary of Changes:
Maintained Process Flow: The call to move_to_second_screen(frame) is retained in the open_file function, so the original flow of transitioning to the second screen remains intact.
External Window: The external window displaying the first seven words is created immediately after the PDF is processed, before transitioning to the second screen.
With these adjustments, you should have a working application that displays the first seven words in an external window while continuing to navigate through the original screens as intended. If you have further questions or need additional modifications, just let me know!
import customtkinter as ctk
import logging
from termcolor import colored
from tkinter import filedialog # Still using this for file dialog
from main import CustomCTkButton # Import the custom button class
from PyPDF2 import PdfReader # Make sure PyPDF2 is installed
def extract_first_seven_words(pdf_path):
"""Extracts the first 7 words from the PDF file."""
with open(pdf_path, 'rb') as file:
reader = PdfReader(file)
text = ''
for page in reader.pages:
text += page.extract_text() + ' '
# Return the first 7 words
return ' '.join(text.split()[:7])
# Function to test if the selected file is a PDF
def testchecker(file_path):
if file_path.endswith('.pdf'):
logging.info(f"PDF accepted: {file_path}")
print(colored(f"PDF accepted: {file_path}", 'green'))
return True
else:
logging.warning(f"Invalid file format: {file_path}")
print(colored(f"Invalid file format: {file_path}", 'red'))
return False
def create_external_window(words):
"""Creates an external customtkinter window to display the first seven words."""
external_window = ctk.CTkToplevel() # Use CTkToplevel for the popup window
external_window.title("PDF Content")
external_window.geometry("400x200")
# Create label for the title
label = ctk.CTkLabel(external_window, text="First 7 Words from PDF:")
label.pack(pady=10)
# Create label to display the words
words_label = ctk.CTkLabel(external_window, text=words, wraplength=350)
words_label.pack(pady=10)
# Create a button to close the window
close_button = ctk.CTkButton(external_window, text="Close", command=external_window.destroy)
close_button.pack(pady=(10, 0))
# Function to create the first screen
def create_first_screen(root):
try:
frame = ctk.CTkFrame(root)
frame.pack(expand=True, fill='both')
def open_file():
file_path = filedialog.askopenfilename(filetypes=[("PDF files", "*.pdf")])
if file_path and testchecker(file_path):
first_seven_words = extract_first_seven_words(file_path)
# Show the first seven words in an external window
create_external_window(first_seven_words)
# Also move to the second screen
move_to_second_screen(frame)
button = CustomCTkButton(frame, text="Upload PDF", command=open_file)
button.place(relx=0.5, rely=0.5, anchor='center')
logging.info("First screen created successfully")
print(colored("First screen created successfully", 'blue'))
except Exception as e:
logging.error(f"Error creating first screen: {e}")
print(colored(f"Error creating first screen: {e}", 'yellow'))
# Function to move to the second screen
def move_to_second_screen(current_frame):
try:
current_frame.pack_forget()
from three_screens.middleman import create_second_screen
create_second_screen(current_frame.master)
logging.info("Moved to second screen successfully")
print(colored("Moved to second screen successfully", 'green'))
except Exception as e:
logging.error(f"Error moving to second screen: {e}")
print(colored(f"Error moving to second screen: {e}", 'orange'))
Key Changes:
CustomTkinter Popup: The create_external_window function now uses ctk.CTkToplevel to create the popup window, making it consistent with the rest of your customtkinter usage.
CustomTkinter Widgets: Used CTkLabel for labels and CTkButton for the close button.
With these updates, the external window will appear using customtkinter styling, maintaining a consistent look and feel with the rest of your application. If you have any more questions or modifications, feel free to ask!
Here’s the updated first_screen.py to utilize the PDFAbstractExtractor class:
python
import customtkinter as ctk
import logging
from termcolor import colored
from tkinter import filedialog
from main import CustomCTkButton # Import the custom button class
from parser.parser import PDFAbstractExtractor # Import the PDFAbstractExtractor class from parser module
from PyPDF2 import PdfReader # Make sure PyPDF2 is installed
# Function to test if the selected file is a PDF
def testchecker(file_path):
if file_path.endswith('.pdf'):
logging.info(f"PDF accepted: {file_path}")
print(colored(f"PDF accepted: {file_path}", 'green'))
return True
else:
logging.warning(f"Invalid file format: {file_path}")
print(colored(f"Invalid file format: {file_path}", 'red'))
return False
def create_external_window(abstract):
"""Creates an external customtkinter window to display the abstract."""
external_window = ctk.CTkToplevel() # Use CTkToplevel for the popup window
external_window.title("Abstract Content")
external_window.geometry("400x300")
# Create label for the title
label = ctk.CTkLabel(external_window, text="Abstract from PDF:")
label.pack(pady=10)
# Create label to display the abstract
abstract_label = ctk.CTkLabel(external_window, text=abstract, wraplength=350)
abstract_label.pack(pady=10)
# Create a button to close the window
close_button = ctk.CTkButton(external_window, text="Close", command=external_window.destroy)
close_button.pack(pady=(10, 0))
# Function to create the first screen
def create_first_screen(root):
try:
frame = ctk.CTkFrame(root)
frame.pack(expand=True, fill='both')
def open_file():
file_path = filedialog.askopenfilename(filetypes=[("PDF files", "*.pdf")])
if file_path and testchecker(file_path):
# Use PDFAbstractExtractor to extract the abstract
extractor = PDFAbstractExtractor(file_path)
abstract_index, abstract_content = extractor.find_abstract()
if abstract_content:
# Show the abstract in an external window
create_external_window(abstract_content)
else:
logging.warning("No abstract found in the PDF.")
print(colored("No abstract found in the PDF.", 'red'))
# Optionally, you can still move to the second screen
move_to_second_screen(frame)
button = CustomCTkButton(frame, text="Upload PDF", command=open_file)
button.place(relx=0.5, rely=0.5, anchor='center')
logging.info("First screen created successfully")
print(colored("First screen created successfully", 'blue'))
except Exception as e:
logging.error(f"Error creating first screen: {e}")
print(colored(f"Error creating first screen: {e}", 'yellow'))
# Function to move to the second screen
def move_to_second_screen(current_frame):
try:
current_frame.pack_forget()
from three_screens.middleman import create_second_screen
create_second_screen(current_frame.master)
logging.info("Moved to second screen successfully")
print(colored("Moved to second screen successfully", 'green'))
except Exception as e:
logging.error(f"Error moving to second screen: {e}")
print(colored(f"Error moving to second screen: {e}", 'orange'))
Summary of Changes:
Import the PDF Extractor: Added an import statement to use PDFAbstractExtractor.
Extract Abstract: The open_file function now creates an instance of PDFAbstractExtractor and calls its find_abstract method to extract the abstract from the selected PDF.
Display Abstract: If an abstract is found, it's displayed in a custom customtkinter external window. If not found, a warning is logged.
With these changes, your application will now allow users to select a PDF file and extract and display the abstract content from that file. If you have any further questions or modifications, feel free to ask!
Example usage
if name == "main":
pdf_path = 'C://Users//Name//Downloads//pdf_test//7008-12244-1-PB.pdf'
extractor = PDFAbstractExtractor(pdf_path)
extractor.process()
import customtkinter as ctk
import logging
from termcolor import colored
from tkinter import filedialog
from main import CustomCTkButton # Import the custom button class
from parser.parser import PDFAbstractExtractor # Import the PDFAbstractExtractor class
def create_external_window(abstract):
"""Creates an external customtkinter window to display the abstract."""
external_window = ctk.CTkToplevel() # Use CTkToplevel for the popup window
external_window.title("Abstract Content")
external_window.geometry("400x300")
# Create label for the title
label = ctk.CTkLabel(external_window, text="Extracted Abstract from PDF:")
label.pack(pady=10)
# Create label to display the abstract
abstract_label = ctk.CTkLabel(external_window, text=abstract, wraplength=350)
abstract_label.pack(pady=10)
# Create a button to close the window
close_button = ctk.CTkButton(external_window, text="Close", command=external_window.destroy)
close_button.pack(pady=(10, 0))
# Function to create the first screen
def create_first_screen(root):
try:
frame = ctk.CTkFrame(root)
frame.pack(expand=True, fill='both')
def open_file():
file_path = filedialog.askopenfilename(filetypes=[("PDF files", "*.pdf")])
if file_path and testchecker(file_path):
# Use PDFAbstractExtractor to extract the abstract
extractor = PDFAbstractExtractor(file_path)
extractor.process() # Process the PDF to find and extract the abstract
# Check if an abstract was found
if extractor.abstract_page_content:
create_external_window(extractor.abstract_page_content) # Display the abstract
else:
logging.warning("No abstract found in the PDF.")
print(colored("No abstract found in the PDF.", 'red'))
# Optionally, you can still move to the second screen
move_to_second_screen(frame)
button = CustomCTkButton(frame, text="Upload PDF", command=open_file)
button.place(relx=0.5, rely=0.5, anchor='center')
logging.info("First screen created successfully")
print(colored("First screen created successfully", 'blue'))
except Exception as e:
logging.error(f"Error creating first screen: {e}")
print(colored(f"Error creating first screen: {e}", 'yellow'))
# Function to move to the second screen
def move_to_second_screen(current_frame):
try:
current_frame.pack_forget()
from three_screens.middleman import create_second_screen
create_second_screen(current_frame.master)
logging.info("Moved to second screen successfully")
print(colored("Moved to second screen successfully", 'green'))
except Exception as e:
logging.error(f"Error moving to second screen: {e}")
print(colored(f"Error moving to second screen: {e}", 'orange'))
Key Changes Made:
Processing the PDF: The open_file function now creates an instance of PDFAbstractExtractor with the selected PDF file path and calls its process method.
External Window for Abstract: After processing, if an abstract is found (i.e., extractor.abstract_page_content is not None), it is displayed in the external window using create_external_window.
Handling No Abstract Found: A warning is displayed if no abstract is found during processing.
With these modifications, when you select a PDF file using the button on the first screen, the application will extract the abstract and display it in a custom tkinter window, while following the structure of your original program. If you have any additional requests or adjustments, feel free to ask!
import customtkinter as ctk
import logging
from termcolor import colored
from tkinter import filedialog
from main import CustomCTkButton # Import the custom button class
from parser.parser import PDFAbstractExtractor # Import the PDFAbstractExtractor class
# Function to create the external window for displaying the abstract
def create_external_window(abstract):
"""Creates an external customtkinter window to display the abstract."""
external_window = ctk.CTkToplevel() # Use CTkToplevel for the popup window
external_window.title("Abstract Content")
external_window.geometry("400x300")
# Create label for the title
label = ctk.CTkLabel(external_window, text="Extracted Abstract from PDF:")
label.pack(pady=10)
# Create label to display the abstract
abstract_label = ctk.CTkLabel(external_window, text=abstract, wraplength=350)
abstract_label.pack(pady=10)
# Create a button to close the window
close_button = ctk.CTkButton(external_window, text="Close", command=external_window.destroy)
close_button.pack(pady=(10, 0))
# Function to create the first screen
def create_first_screen(root):
try:
frame = ctk.CTkFrame(root)
frame.pack(expand=True, fill='both')
def open_file():
file_path = filedialog.askopenfilename(filetypes=[("PDF files", "*.pdf")])
if file_path: # Only proceed if a file is selected
# Use PDFAbstractExtractor to extract the abstract
extractor = PDFAbstractExtractor(file_path)
extractor.process() # Process the PDF to find and extract the abstract
# Check if an abstract was found
if extractor.abstract_page_content:
create_external_window(extractor.abstract_page_content) # Display the abstract
else:
logging.warning("No abstract found in the PDF.")
print(colored("No abstract found in the PDF.", 'red'))
# You may choose to move to the second screen if needed
move_to_second_screen(frame)
button = CustomCTkButton(frame, text="Upload PDF", command=open_file)
button.place(relx=0.5, rely=0.5, anchor='center')
logging.info("First screen created successfully")
print(colored("First screen created successfully", 'blue'))
except Exception as e:
logging.error(f"Error creating first screen: {e}")
print(colored(f"Error creating first screen: {e}", 'yellow'))
# Function to move to the second screen
def move_to_second_screen(current_frame):
try:
current_frame.pack_forget()
from three_screens.middleman import create_second_screen
create_second_screen(current_frame.master)
logging.info("Moved to second screen successfully")
print(colored("Moved to second screen successfully", 'green'))
except Exception as e:
logging.error(f"Error moving to second screen: {e}")
print(colored(f"Error moving to second screen: {e}", 'orange'))
Key Adjustments:
Removed testchecker(): The check for validating the PDF file based on the extension is removed, assuming the only files being selected are PDFs as indicated by the file dialog filter.
Integrated PDFAbstractExtractor: The open_file() function now directly creates an instance of PDFAbstractExtractor, calls process(), and subsequently checks for the extracted abstract content.
Handling Logic: It checks if an abstract was found and calls the create_external_window() function to display it. If no abstract is found, it logs a warning and prints a message in red.
This structure should work seamlessly with the PDFAbstractExtractor functionality as defined in your parser.py. If there are any other specific requirements or further adjustments you'd like, just let me know!