File size: 3,784 Bytes
7f8b26c
 
 
 
 
24f4089
 
 
 
7f8b26c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
from typing import List, Tuple
import logging

import gradio as gr

try:
    from .services import identify_vague_statements
except ImportError:
    from services import identify_vague_statements


def create_editable_section(label, js_script, submit_fn, textbox):
    with gr.Accordion(f"Edit {label}", open=False) as acc:
        output_text = gr.HTML(label="Highlighted Text", elem_id=f"highlighted_textarea_{label}", value=textbox)
        output_text_suggestion = gr.Textbox(label="Suggestions", lines=5, interactive=True)
        with gr.Row():
            submit_button = gr.Button("Run Editorial AI", size="small")
            accept_button = gr.Button("Apply Changes", size="small")

        edit_pairs = gr.State([])

        def submit_callback(default_text):
            result = submit_fn(default_text)
            pairs = result["pairs"]
            edit_pairs.value = pairs
            return result["html"], result["suggestions"]

        def update_change(changes, original):
            for old_text, new_text in changes:
                modified = original.replace(old_text, new_text)
            return modified

        # pylint: disable=no-member
        submit_button.click(
            # fn=submit_fn,
            fn=submit_callback,
            inputs=textbox,
            outputs=[output_text, output_text_suggestion]
        )

        # pylint: disable=no-member
        accept_button.click(
            fn=update_change,
            inputs=[edit_pairs, textbox],
            outputs=textbox
        )

        # Add custom JavaScript to make the output area editable
        gr.HTML(f"<script>{js_script}</script>")
    return acc


def highlight_text(input_section: str) -> Tuple[str, List[str], List[str], List[str]]:
    try:
        # Escape special characters for HTML
        input_section = input_section.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
        vague_statements, alternative_texts, reasons = identify_vague_statements(input_section)

        highlighted_text = input_section
        for vague_statement in vague_statements:
            vague_statement = vague_statement.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
            highlighted_text = highlighted_text.replace(vague_statement, f'<mark>{vague_statement}</mark>')

        logging.info("Success: Highlight text")
        return highlighted_text, vague_statements, alternative_texts, reasons

    except Exception as e:
        logging.error("Error: %s", e)
        # return input_section, [], [], []
        raise gr.Error("Error in Extracting vague statements..")


def update_highlighted_text(default_text: str):
    gr.Info("Running Editorial AI..")
    # progress = gr.Progress()
    # progress(0, desc="Starting...")
    highlighted_text, vague_statements, alternative_texts, reasons = highlight_text(default_text)
    suggestions = ""
    pairs = []
    # for vague, alternative, reason in progress.tqdm(zip(vague_statements, alternative_texts, reasons)):
    for vague, alternative, reason in zip(vague_statements, alternative_texts, reasons):
        pairs.append((vague, alternative))
        suggestions += f"Vague Statement: {vague}\nReason: {reason}\nAlternative Text: {alternative}\n\n"

    html = f"""
        <div id="highlighted_textarea" class="custom-textarea" contenteditable="true">
            {highlighted_text}
        </div>
        <script>
            window.highlightTexts = [{', '.join([f'`{sentence.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")}`' for sentence in vague_statements])}];
        </script>
    """

    result = {
        "html": html,
        "suggestions": suggestions,
        "pairs": pairs
    }

    logging.info("Highlighted the text successfully..")
    return result