Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
39 kB
3
Indexable
Never
import PyPDF2
import re
import tkinter as tk
from tkinter import filedialog
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
from docx.oxml.ns import nsdecls
from docx.oxml.ns import qn
import easygui
from docx.oxml import parse_xml
from docx.shared import Inches
from PIL import Image, ImageDraw, ImageFont


class Careplan():
    def create_care_plan(self,patient_name, dob, phone_number, chronic_conditions, extracted_data):
        document = Document()
        def create_image():
            # Add a section to the document
            section = document.sections[0]

            # Set the page width and height to match the photo size
            section.page_width = Inches(8.5)
            section.page_height = Inches(11)

            # Adjust the margins to 0 inches
            section.left_margin = Inches(0)
            section.right_margin = Inches(0)
            section.top_margin = Inches(0)
            section.bottom_margin = Inches(0)

            # Add a new paragraph to the document
            paragraph = document.add_paragraph()
            image_path = r"pic.png"
            if not image_path:
                print("Exception coming in image Path!")
            # run = paragraph.add_run().add_picture(image_path, width=section.page_width, height=section.page_height)

            image = Image.open(image_path)
            draw = ImageDraw.Draw(image)

            table_font_size = 100
            table_width = image.width // 1.5
            table_height = table_font_size * 7  # Height of the table based on the number of rows

            table_position_x = (image.height - table_height) // 6.5
            table_position_y = (image.height - table_height) // 2.25  # Centered vertically

            table_border_color = (0, 0, 0)  # Black border color
            table_border_width = 4  # Border width in pixels
            table_border_height = 4

            draw.rectangle((table_position_x, table_position_y, table_position_x + table_width,
                            table_position_y + table_height))  # Fill the table background with the specified color

            # Draw horizontal borders
            draw.rectangle((table_position_x, table_position_y, table_position_x + table_width,
                            table_position_y + table_border_height),
                           fill=table_border_color)  # Top border
            draw.rectangle((table_position_x, table_position_y + table_height - table_border_height,
                            table_position_x + table_width,
                            table_position_y + table_height), fill=table_border_color)  # Bottom border

            # Draw vertical borders
            draw.rectangle((table_position_x, table_position_y, table_position_x + table_border_width,
                            table_position_y + table_height),
                           fill=table_border_color)  # Left border
            draw.rectangle(
                (table_position_x + table_width - table_border_width, table_position_y, table_position_x + table_width,
                 table_position_y + table_height), fill=table_border_color)  # Right border

            # Define the text and font properties for the table cells
            cell_text_font = ImageFont.truetype("arial.ttf", size=table_font_size)
            cell_text_color = (31, 73, 125)  # Black color

            # Draw the table rows
            row_padding = 100  # Padding between the rows
            row_height = table_font_size + row_padding

            # Draw the first row
            row1_position_x = table_position_x
            row1_position_y = table_position_y
            draw.rectangle((row1_position_x, row1_position_y, row1_position_x + table_width,
                            row1_position_y + row_height))  # Draw the border for the first row
            draw.text((row1_position_x + row_padding, row1_position_y + row_padding), f'Patient Name: {patient_name}',
                      fill=cell_text_color, font=cell_text_font)
            # Draw the second row
            row2_position_x = table_position_x
            row2_position_y = row1_position_y + row_height
            draw.rectangle((row2_position_x, row2_position_y, row2_position_x + table_width,
                            row2_position_y + row_height))  # Draw the border for the second row
            draw.text((row2_position_x + row_padding, row2_position_y + row_padding), f'Date of Birth: {dob}',
                      fill=cell_text_color, font=cell_text_font)

            # Draw the third row
            row3_position_x = table_position_x
            row3_position_y = row2_position_y + row_height
            draw.rectangle((row3_position_x, row3_position_y, row3_position_x + table_width,
                            row3_position_y + row_height))  # Draw the border for the third row
            draw.text((row3_position_x + row_padding, row3_position_y + row_padding), f'Phone Number: {phone_number}',
                      fill=cell_text_color, font=cell_text_font)

            # Add the instructions at the end of the front page

            instructions_text_1 = "Before your next Appointment:\n• Take your medications regularly.\n• Keep up your diet plans.\n• Be up to date on your blood work and immunizations as advised\n by your healthcare provider."
            instructions_font_size = 60
            instructions_text_font = ImageFont.truetype("arial.ttf", size=instructions_font_size)
            instructions_text_width, instructions_text_height = draw.textsize(instructions_text_1, font=cell_text_font)
            instructions_position_x = 300
            instructions_position_y = image.height - instructions_text_height - 1100  # 50 pixels from the bottom
            draw.text((instructions_position_x, instructions_position_y), instructions_text_1, fill=cell_text_color,
                      font=instructions_text_font, spacing=30)

            Chronic_condition_font_size = 60
            Chronic_condition_font = ImageFont.truetype("arial.ttf", size=Chronic_condition_font_size)
            final_chronic_condition = ", ".join(chronic_conditions) if len(chronic_conditions) > 1 else chronic_conditions[0]
            Chronic_condition_text = f'Your Chronic Conditions: {final_chronic_condition}'
            Chronic_condition_text_width, Chronic_condition_text_height = draw.textsize(Chronic_condition_text,
                                                                                        font=Chronic_condition_font)
            Chronic_condition_x = (image.width - Chronic_condition_text_width) // 2  # Centered horizontally
            Chronic_condition_y = image.height - Chronic_condition_text_height - 900  # 50 pixels from the bottom
            draw.text((Chronic_condition_x, Chronic_condition_y), Chronic_condition_text, fill=cell_text_color,
                      font=Chronic_condition_font, spacing=30)

            # Save the modified image
            modified_image_path = r"C:\Users\HP\Desktop\Careplan\Modified_Image.png"
            try:
                image.save(modified_image_path)
                paragraph.add_run().add_picture(modified_image_path, width=section.page_width,
                                            height=section.page_height)
            except Exception as e:
                print(f"Exception coming: {e}")

                #Adjust the page margins to default
            rest_page = document.add_section()
            rest_page.left_margin = Inches(1)
            rest_page.right_margin = Inches(1)
            rest_page.top_margin = Inches(1)
            rest_page.bottom_margin = Inches(1)
        create_image()
        def add_section(title, content):
            heading = document.add_heading(level=1)
            run = heading.add_run(title)
            run.font.name = 'Cambria Math'
            run.font.size = Pt(16)
            run.font.color.rgb = parse_xml(
                r'<w:color xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:val="0070C0"/>').val
            shading_elm = parse_xml(r'<w:shd {} w:fill="E6F3FF"/>'.format(nsdecls('w')))
            heading._element.append(shading_elm)
            run.bold = True

            # Check if content should be formatted as bullet points
            if title in ['Symptoms:', 'Dietary guidelines:']:
                for item in content:
                    paragraph = document.add_paragraph()
                    paragraph.style = document.styles['List Bullet']
                    run = paragraph.add_run(item.strip())
                    run.font.size = Pt(12)
                    run.font.bold = False
            else:
                paragraph = document.add_paragraph(content)
                paragraph.style = 'Normal'
                run = paragraph.runs[0] if paragraph.runs else paragraph.add_run()
                run.font.size = Pt(12)
                run.font.bold = False

        # Function to add a table with two columns
        def add_table(lines):
            num_lines = len(lines)
            num_rows = (num_lines + 1) // 2  # Calculate the number of rows for the tablec
            table = document.add_table(rows=num_rows, cols=2)
            table.autofit = False

            # Set table style
            table.style = 'Table Grid'

            # Set cell margins
            for row in table.rows:
                for cell in row.cells:
                    cell_margin = cell._element.xpath('.//w:tcMar')
                    if cell_margin:
                        cell_margin[0].set(qn('w:left'), '60')
                        cell_margin[0].set(qn('w:right'), '60')

            # Set cell borders
            for row in table.rows:
                for cell in row.cells:
                    for border in cell._element.xpath('.//w:tcBorders'):
                        border.set(qn('w:sz'), '2')
                        border.set(qn('w:val'), 'single')

            # Set vertical alignment to center
            for row in table.rows:
                for cell in row.cells:
                    for paragraph in cell.paragraphs:
                        for run in paragraph.runs:
                            run.font.size = Pt(12)
                            run.font.bold = False
                            paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
                            cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER

            # Populate table cells with lines
            for i, line in enumerate(lines):
                row_idx = i // 2  # Calculate the row index
                col_idx = i % 2  # Calculate the column index
                cell = table.cell(row_idx, col_idx)
                cell.text = line

        care_plans = {
            'Obesity': {
                'definition': 'Overweight and obesity are defined as abnormal or excessive fat accumulation that presents a risk to health. A body mass index (BMI) over 25 is considered overweight, and over 30 is the obesity category.',
                'symptoms': 'Excess body fat, particularly around the waist, Sweating more than usual, Snoring, Trouble sleeping, Inability to perform simple physical tasks you could easily perform before weight gain.',
                'treatment_goals': 'The treatment goal for obesity is to achieve a body mass index (BMI) range between 18.5-24.9 kg/m² for a healthy weight.',
                'preventive_measures': 'To prevent obesity, it is recommended to limit unhealthy foods such as refined grains and sweets, potatoes, red meat, and processed meat. Staying physically active by incorporating a 10-minute walk after each meal, adjusted to your capacity and fitness level, is important. It is also advised to reduce sedentary activities like watching television, videotapes, and playing computer games.'
            },

            'Asthma': {
                'definition': 'Asthma is a condition in which the airways get narrow and swell and may produce extra mucus.',
                'symptoms': 'Wheezing, coughing, and chest tightness becoming severe and constant, Being too breathless to eat, speak, or sleep, Breathing faster, A fast heartbeat, Drowsiness, confusion, exhaustion, or dizziness, Blue lips or fingers, Fainting.',
                'treatment_goals': 'The treatment goal for asthma is to attain a normal breathing rate and manage symptoms to prevent severe and constant wheezing, coughing, and chest tightness.',
                'preventive_measures': 'To prevent asthma symptoms, it is recommended to try to know and avoid your asthma triggers, keep your inhaler with you always, keep nebulizing yourself, and stay away from all kinds of allergens and avoid smoking.'
            },

            'Hypertension': {
                'definition': 'Hypertension is a common condition in which the long-term force of the blood against the artery walls is high enough to cause cardiovascular diseases.',
                'symptoms': 'Blurry or double vision, Lightheadedness/Fainting, Fatigue, Headache, Heart palpitations.',
                'treatment_goals': 'The treatment goal for hypertension is to keep your blood pressure around the normal range, typically 120/80 mmHg.',
                'preventive_measures': 'To prevent hypertension, it is recommended to try to monitor blood pressure daily and avoid stress triggers, cut your salt and sugar intake, avoid fatty foods, and quit smoking if you currently smoke since smoking damages blood vessels.'
            },

            'Hyperlipidemia': {
                'definition': 'Hyperlipidemia is a medical term for abnormally high levels of fats (lipids) in the blood, which include cholesterol and triglycerides.',
                'symptoms': 'Chest pain or pressure (angina), Blockage of blood vessels in the brain and heart, High blood pressure, Heart attack, Stroke.',
                'treatment_goals': 'The treatment goals for hyperlipidemia are to lower LDL cholesterol levels below specific target values (e.g., below 100 mg/dL), increase HDL cholesterol levels to desired ranges (e.g., above 50 mg/dL), and control triglyceride levels to recommended levels (e.g., below 150 mg/dL).',
                'preventive_measures': 'To prevent hyperlipidemia, it is recommended to limit alcohol consumption (too much alcohol can lead to serious health problems), lose weight (carrying even a few extra pounds contributes to high cholesterol), and decrease consumption of saturated fats to reduce LDL cholesterol levels.'
            },

            'Diabetes Mellitus': {
                'definition': 'Diabetes is a chronic disease that occurs either when the pancreas does not produce enough insulin (type 1) or when the body cannot effectively use the insulin it produces (type 2).',
                'symptoms': 'Frequent urination, Excessive thirst and hunger, Unexplained weight loss, Sudden vision changes, Tingling or numbness in the hands or feet, Feeling very tired much of the time.',
                'treatment_goals': 'The treatment goal for diabetes mellitus is to keep blood glucose levels as close to normal as safely possible. Regularly checking blood glucose levels, such as before breakfast (80-110 mg/dL), is important.',
                'preventive_measures': 'To prevent diabetes mellitus, it is recommended to limit sugar, white flour, and other refined grains, as well as starchy vegetables that can spike glucose levels. Managing both emotional and physical stress is important to avoid worsening insulin resistance. Engaging in higher levels of physical activity, such as more than 90 minutes per day, can reduce the risk of diabetes by 28%.'
            },

            'Coronary Artery Disease (CAD)': {
                'definition': 'Coronary artery disease (CAD) is caused by plaque build-up in the wall of the arteries that supply blood to the heart. Plaque is made up of cholesterol deposits.',
                'symptoms': 'Chest pain or discomfort (angina), Pressure, tightness, squeezing, or heavy sensation in the chest, Radiating pain to the arms (usually left arm), shoulders, jaw, neck, or back, Shortness of breath, Fatigue and lack of energy, Irregular heartbeats or palpitations, Dizziness or lightheadedness, Unexplained sweating.',
                'treatment_goals': 'The treatment goal for coronary artery disease is to prevent disease progression and reduce the risk of complications such as heart attack or heart failure.',
                'preventive_measures': 'To prevent coronary artery disease, it is recommended to maintain a healthy lifestyle by eating well, exercising regularly, maintaining a healthy weight, and avoiding smoking and excessive alcohol consumption. Controlling risk factors such as blood pressure, blood sugar, and cholesterol levels is important, and finding healthy ways to cope with stress is advised. Regular check-ups and routine screenings with a healthcare provider are also recommended.'
            },

            'Anemia': {
                'definition': 'Anemia is a condition in which the person lacks enough healthy red blood cells to carry adequate oxygen to the body\'s tissues.',
                'symptoms': 'Fatigue and weakness, Pale or yellowish skin, Irregular heartbeats, Shortness of breath, Dizziness or lightheadedness, Chest pain.',
                'treatment_goals': 'The treatment goals for anemia are to increase hemoglobin levels and improve oxygen-carrying capacity, as well as alleviate symptoms of fatigue and weakness. Additionally, replenishing and maintaining adequate levels of deficient nutrients, such as iron or vitamin B12, is important.',
                'preventive_measures': 'To prevent anemia, it is recommended to avoid taking iron supplements along with calcium supplements, as it can hinder the absorption of iron. It is also advised to avoid coffee, tea, cold drinks, and sodas along with your meal, as they can hinder the absorption of iron in the blood. Poor diet is a primary reason why people develop anemia, so maintaining a balanced and nutritious diet is crucial.'
            },

            'Rheumatoid Arthritis': {
                'definition': 'Rheumatoid arthritis (RA) is a chronic, progressive, and disabling autoimmune disease. It causes inflammation, swelling, and pain in and around the joints and can affect other body organs.',
                'symptoms': 'Joint pain, tenderness and stiffness, Inflammation in and around the joints, Restricted movement of the joints, Warm red skin over the affected joint, Weakness and muscle wasting.',
                'treatment_goals': 'The treatment goals for rheumatoid arthritis include slowing or preventing additional joint damage, maintaining current levels of function, and providing relief from fatigue and weakness.',
                'preventive_measures': 'To prevent or manage rheumatoid arthritis symptoms, warm water bottles can be used for pain relief. If experiencing a flare-up, it\'s important to rest and give your joints a chance to recover. Additionally, maintaining a healthy weight is important to reduce pressure on weight-bearing joints like hips and knees.'
            },

            'Hepatitis C': {
                'definition': 'Hepatitis C is an inflammation of the liver caused by the hepatitis C virus. The hepatitis C virus is a bloodborne virus, and most infections occur through exposure to blood from unsafe injection practices, unsafe healthcare, unscreened blood transfusions, injection drug use, and sexual practices that lead to exposure to blood.',
                'symptoms': 'Fatigue and weakness, Jaundice (yellowing of the skin and eyes), Abdominal pain or discomfort, Loss of appetite, Nausea and vomiting, Dark urine, Pale or clay-colored stools, Joint pain, Muscle aches.',
                'treatment_goals': 'The treatment goals for Hepatitis C are to achieve sustained virologic response (SVR) and prevent liver damage and disease progression.',
                'preventive_measures': 'To prevent Hepatitis C, it is important to practice safe injection practices and avoid sharing needles or other drug paraphernalia. Practice safe sex by using barrier methods, such as condoms, and consider getting vaccinated against hepatitis B. It is also crucial to avoid direct contact with infected blood or blood products and ensure proper sterilization and hygiene practices in healthcare settings.'
            },

            'Osteoarthritis': {
                'definition': 'Osteoarthritis occurs when the cartilage that cushions the ends of bones in your joints gradually deteriorates.',
                'symptoms': 'Joint pain, tenderness and stiffness, Inflammation in and around the joints, Restricted movement of the joints, Warm red skin over the affected joint, Weakness and muscle wasting.',
                'treatment_goals': 'The treatment goals for osteoarthritis include slowing or preventing additional joint damage, maintaining current levels of function, and providing relief from fatigue and weakness.',
                'preventive_measures': 'To prevent or manage osteoarthritis symptoms, warm water bottles can be used for pain relief. If experiencing a flare-up, it\'s important to rest and give your joints a chance to recover. Additionally, maintaining a healthy weight is important to reduce pressure on weight-bearing joints like hips and knees.'
            },

            'Congestive Heart Failure (CHF)': {
                'definition': 'Congestive heart failure (CHF), also called heart failure, is a serious condition in which the heart doesn\'t pump blood as efficiently as it should.',
                'symptoms': 'Shortness of breath with activity or when lying down, Fatigue and weakness, Swelling in the legs, ankles, and feet, Rapid or irregular heartbeat, Reduced ability to exercise, Persistent cough or wheezing with white or pink blood-tinged mucus.',
                'treatment_goals': 'The treatment goals for congestive heart failure are to optimize cardiac function and reduce the workload on the heart, manage fluid retention and maintain appropriate fluid balance, and control blood pressure to reduce strain on the heart.',
                'preventive_measures': 'To prevent congestive heart failure, it is recommended to stop smoking or, better yet, not start, as smoking is a major factor in arterial damage that can cause heart failure. Restricting daily fluid intake as per healthcare provider instructions and living a healthy lifestyle can also help lower the risk for heart disease and heart attack.'
            },

            'Chronic Obstructive Pulmonary Disease (COPD)': {
                'definition': 'Chronic obstructive pulmonary disease, or COPD, refers to a group of diseases that cause airflow blockage and breathing-related problems. It mainly includes emphysema and chronic bronchitis.',
                'symptoms': 'Wheezing, coughing, and chest tightness becoming severe and constant, Being too breathless to eat, speak, or sleep, Breathing faster, A fast heartbeat, Drowsiness, confusion, exhaustion, or dizziness, Blue lips or fingers, Fainting',
                'treatment_goals': 'The treatment goals for COPD are to improve lung function and increase the ability to breathe effectively, ultimately attaining a normal breathing rate.',
                'preventive_measures': 'To prevent COPD symptoms, it is recommended to try to know and avoid your asthma triggers, keep your inhaler with you always, keep nebulizing yourself, and stay away from all kinds of allergens and avoid smoking.'
            },

            'Chronic Kidney Disease (CKD)': {
                'definition': 'Chronic kidney disease, also called chronic kidney failure, involves a gradual loss of kidney function. CKD has five stages and it can progress to end-stage renal disease, which is fatal without artificial filtering (dialysis) or a kidney transplant.',
                'symptoms': 'Weight loss and poor appetite, Swollen ankles, feet, or hands – as a result of water retention (edema), Shortness of breath, Tiredness, Blood in your urine, An increased need to pee – particularly at night.',
                'treatment_goals': 'The treatment goals for chronic kidney disease are to slow the progression of CKD and manage underlying conditions that contribute to it, such as high blood pressure, diabetes, and autoimmune disorders.',
                'preventive_measures': 'To prevent or manage chronic kidney disease, it is recommended to restrict daily fluid intake as per healthcare provider instructions, engage in regular exercise (2-3 hours per day) to reduce the risk of developing kidney disease, and establish a healthy lifestyle to reduce symptoms.'
            },

            'Hypothyroidism': {
                'definition': 'Hypothyroidism is a common condition where the thyroid doesn\'t create and release enough thyroid hormone into the bloodstream.',
                'symptoms': 'Tiredness, More sensitivity to cold, Constipation, Dry skin, Weight gain, Puffy face, Hoarse voice.',
                'treatment_goals': 'The treatment goal for hypothyroidism is to restore thyroid hormone levels to the normal range.',
                'preventive_measures': 'To prevent or manage hypothyroidism, it is recommended to take thyroxine on an empty stomach, as directed. Avoid smoking, as the toxins released during smoking can make the thyroid gland oversensitive, leading to thyroid disorders. Additionally, managing stress is important, as stress is one of the major contributors to many health disorders, including thyroid disease.'
            }
        }

        # # Add company name with customized styling
        # company_name = document.add_paragraph()
        # company_name_run = company_name.add_run("AZZ Medical Associates")
        # company_name_run.bold = True
        # company_name_run.font.size = Pt(46)
        # company_name_run.font.color.rgb = parse_xml(
        #     r'<w:color xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:val="2E74B5"/>').val
        # company_name.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
        #
        # # Set font style and size for the title
        # title = document.add_paragraph()
        # title_run = title.add_run("Care Plan")
        # title_run.bold = True
        # title_run.font.size = Pt(36)
        # title_run.font.color.rgb = parse_xml(
        #     r'<w:color xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:val="2E74B5"/>').val
        # title.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
        #
        # # Add patient information with customized styling
        # patient_info = document.add_paragraph()
        # patient_info_run = patient_info.add_run("Patient Information:")
        # patient_info_run.bold = True
        # patient_info_run.font.size = Pt(16)
        # patient_info_run.font.color.rgb = parse_xml(
        #     r'<w:color xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:val="2E74B5"/>').val
        # patient_info.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
        #
        # # Add a table with a single row and three cells
        # table = document.add_table(rows=1, cols=3)
        #
        # # Apply table style
        # table.style = 'Table Grid'
        #
        # # Merge the cells in the first row and adjust the width of the first column
        # table.columns[0].width = Pt(200)  # Adjust the width of the first column (in points)
        #
        # table_cell = table.cell(0, 0)
        # table_cell.merge(table.cell(0, 2))
        #
        # # Add the patient information as paragraphs in the merged cell
        # paragraph = table_cell.paragraphs[0]
        # run = paragraph.add_run(f'Patient Name: {patient_name}')
        # run.bold = True
        # run.font.size = Pt(26)  # Increase font size for patient name
        # paragraph.style = 'Heading2'
        #
        # paragraph = table_cell.add_paragraph()
        # run = paragraph.add_run(f'Date of Birth: {dob}')
        # run.bold = True
        # run.font.size = Pt(26)  # Increase font size for date of birth
        # paragraph.style = 'Heading2'
        #
        # paragraph = table_cell.add_paragraph()
        # run = paragraph.add_run(f'Phone Number: {phone_number}')
        # run.bold = True
        # run.font.size = Pt(26)  # Increase font size for phone number
        # paragraph.style = 'Heading2'
        #
        # document.add_page_break()

        # Combine definitions of chronic conditions
        combined_definition = '\n\n'.join(
            [f"What is {condition.capitalize()}?\n\n{care_plans[condition]['definition']}" for condition in
             chronic_conditions if condition in care_plans])
        combined_symptoms = []
        for condition in chronic_conditions:
            if condition in care_plans:
                symptoms = care_plans[condition]['symptoms'].split('\n')
                combined_symptoms.extend(symptoms)
        combined_treatment_goals = '\n\n'.join(
            [f"{condition.capitalize()}:\n\n{care_plans[condition]['treatment_goals']}" for condition in
             chronic_conditions if condition in care_plans])
        combined_preventive_measures = '\n\n'.join(
            [f"{condition.capitalize()}:\n\n{care_plans[condition]['preventive_measures']}" for condition in
             chronic_conditions if condition in care_plans])
        if chronic_conditions:
            add_section('Definitions:', combined_definition)
            add_section("Symptoms:", combined_symptoms)
            add_section("Treatment Goals:", combined_treatment_goals )
            add_section("Preventive Measures:", combined_preventive_measures)
            # Add extracted data from the PDF as a table
            document.add_paragraph('Medications List', style='Heading1').alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
            extracted_lines = extracted_data.split('\n')
            add_table(extracted_lines)
            # add_section('Dietary guidelines:', combined_dietary_guidelines)
        heading = "DIETARY GUIDELINES TO FOLLOW"
        paragraph = document.add_paragraph(heading)
        paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
        paragraph.style = "Heading 1"

        # Define the number of rows and columns in the table
        rows = 6
        cols = 2

        # Create the table with the specified number of rows and columns
        table = document.add_table(rows=rows, cols=cols)

        # Set the width of the columns
        table.autofit = False
        table.columns[0].width = Inches(2)
        table.columns[1].width = Inches(4)

        # Set the height of the rows
        for row in table.rows:
            row.height = Inches(1)

        # Access the cells in the table and set their content
        data = [
            ("CEREALS",
             "Choose complex carbohydrates and wholegrain cereals over refined ones. For example 1 cup oatmeal, 2 wholegrain bread slices, 1 cup rice, etc."),
            ("FRUITS",
             "Prefer the intake of fruits in moderation on a daily basis. For example ½ cup grapes, 1 small apple, 2 medium slices watermelon, 1 small banana, etc."),
            ("VEGETABLES",
             "Prefer the intake of vegetables on a daily basis. For example ½ cup spinach, ½ cup cauliflower, ½ cup broccoli, ½ cup cabbage, etc."),
            ("MEAT",
             "Prefer the white meat over the red one. Prefer the egg intake as well. For example 2 oz chicken or fish, 1 boiled egg whites, etc."),
            ("DAIRY PRODUCTS",
             "Choose the low-fat dairy products in your diet. For example 1 cup low-fat milk, 2/3 cup low-fat yogurt, etc."),
            ("HEALTHY FATS",
             "Prefer nuts and also the olive oil for the salad dressing. For example 1 tsp olive oil, mustard oil, 6 almonds, etc.")
        ]

        for i, (header, content) in enumerate(data):
            cell_header = table.cell(i, 0)
            cell_content = table.cell(i, 1)

            cell_header.width = Inches(2)
            cell_content.width = Inches(4)

            # Set the paragraph alignment to center for the header cell
            cell_header_paragraph = cell_header.paragraphs[0]
            cell_header_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

            # Add a new run to the paragraph and set it to bold
            run = cell_header_paragraph.add_run()
            run.text = header
            run.bold = True

            cell_content.text = content

        # Change the style of the table
        table.style = "Table Grid"
        # Save the care plan document
        document.save(f"care_plan_{patient_name}.docx")
        print(f'Care plan created for {patient_name}.')


class ExtractDrugData(Careplan):
    def extract_drug_data(self, pdf_path):
        with open(pdf_path, 'rb') as file:
            doc = PyPDF2.PdfReader(file)
            drug_sig_list = []
            drug = ""
            sig = ""
            for page in doc.pages:
                page_text = page.extract_text()
                lines = page_text.split('\n')
                pattern = r"(Sig:.*)"
                for i, line in enumerate(lines):
                    if "DRUG:" in line:
                        if drug and sig:
                            drug_sig_list.append(drug)
                            drug_sig_list.append(sig)
                        drug = lines[i+1]
                        sig = ""
                    elif re.search(pattern, line):
                        result = re.findall(pattern, line)
                        if result:
                            sig = result[0]
            if drug and sig:
                drug_sig_list.append(drug)
                drug_sig_list.append(sig)
            extracted_data = "\n".join(drug_sig_list)
            return extracted_data

    def browse_pdf_file(self):
        root = tk.Tk()
        root.withdraw()
        file_path = filedialog.askopenfilename(filetypes=[('PDF Files', '*.pdf')])
        if not file_path:
            exit()
        return file_path


class CareplanGUI(ExtractDrugData):
    def select_chronic_conditions(self):
        msg = "Select chronic conditions:"
        title = "Chronic Conditions Selection"
        choices = ["Hypertension", "Obesity", "Asthma", "Hyperlipidemia", "Diabetes Mellitus", "Coronary Artery Disease (CAD)", "Anemia", "Hypothyroidism",
                   "Rheumatoid Arthritis", "Hepatitis C", "Osteoarthritis", "Congestive Heart Failure (CHF)", "Chronic Obstructive Pulmonary Disease (COPD)", "Chronic Kidney Disease (CKD)"]
        choices.sort()
        selected_conditions = easygui.multchoicebox(msg, title, choices)
        if not selected_conditions:
            exit()
        return selected_conditions

    def select_lines(self, choices):
        msg = "Select the Drugs and Sig to include in the Careplan"
        title = "Drugs and Sig selection"
        selected_lines = easygui.multchoicebox(msg, title, choices)
        if not selected_lines:
            exit()
        return selected_lines

    def prompt_patient_info(self):
        def get_valid_name():
            while True:
                message = "Enter Patient name (letters only):"
                title = "Patient-Name"
                name = easygui.enterbox(message, title)

                if name is None:
                    exit()  # Terminate the program if Cancel is pressed

                # Check if the name contains only letters
                if re.match(r"(^[a-zA-Z ]{3,}$)", name):
                    return name
                else:
                    easygui.msgbox("Invalid name. Please enter letters only.", "Error")

        def get_valid_date():
            while True:
                message = "Enter patient date of birth (MM/DD/YYYY):"
                title = "Date of Birth"
                dob = easygui.enterbox(message, title)

                if dob is None:
                    exit()  # Terminate the program if Cancel is pressed

                # Check if the date format is correct
                if re.match(r"^([1-9]|1[0-2])/([1-9]|1\d|2\d|3[01])/((19|20)\d{2})$", dob):
                    return dob
                else:
                    easygui.msgbox("Invalid Date of Birth. Please enter correct format", "Error")

        def get_valid_phone():
            while True:
                message = "Enter patient phone-number (123-444-4567)"
                title = "Phone-Number"
                num = easygui.enterbox(message, title)

                if num is None:
                    exit()  # Terminate the program if Cancel is pressed

                # Check if the date format is correct
                if re.match(r"^\d{3}-\d{3}-\d{4}$", num):
                    return num
                else:
                    easygui.msgbox("Invalid format of phone-number. Please Enter correct Format", "Error")

        name, dob, phone = get_valid_name(), get_valid_date(), get_valid_phone()
        return name, dob, phone






        # while True:
        #     patient_name = easygui.enterbox('Enter patient name:')
        #
        #     if re.match("^[a-zA-Z]+$", patient_name):
        #         name = patient_name
        #     else:
        #         easygui.msgbox("Invalid name. Please enter letters only.", "Error")
        #     dob = easygui.enterbox("Enter patient date of birth (MM/DD/YYYY):")
        #     if not dob:
        #         exit()
        #     if re.match(r"^(0[1-9]|1[0-2])/(0[1-9]|1\d|2\d|3[01])/((19|20)\d{2})$", dob):
        #         date = dob
        #     phone_number = easygui.enterbox("Enter patient phone number:")
        #     if not phone_number:
        #         exit()
        #     return name, date, phone_number

    def merge_data_and_create_care_plan(self):
        # Prompt for patient info
        patient_name, dob, phone_number = self.prompt_patient_info()

        # Select chronic conditions
        chronic_conditions = self.select_chronic_conditions()

        # Browse and extract data from the PDF file
        pdf_file_path = self.browse_pdf_file()
        extracted_data = self.extract_drug_data(pdf_file_path)

        # Select the lines to include in the care plan
        # selected_lines = self.select_lines(extracted_data)
        selected_lines = self.select_lines(extracted_data.split('\n'))

        # Create the care plan document
        self.create_care_plan(patient_name, dob, phone_number, chronic_conditions, '\n'.join(selected_lines))


patient = CareplanGUI()
patient.merge_data_and_create_care_plan()