File size: 5,731 Bytes
38d999c
 
 
 
 
 
 
 
23672df
252a2d4
38d999c
 
 
 
 
 
b0d997e
 
713b4c4
b0d997e
38d999c
 
 
7ac9c82
c4bf747
4beadd4
38d999c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b484679
38d999c
4beadd4
38d999c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05e9755
38d999c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4bf747
 
 
 
 
 
 
38d999c
 
 
 
 
 
 
 
 
 
 
 
d57f0a6
0730709
 
 
d57f0a6
 
636c30d
d57f0a6
 
 
 
 
 
 
38d999c
 
 
 
 
 
945af81
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
from annotated_text import annotated_text
from bs4 import BeautifulSoup
from gramformer import Gramformer
import streamlit as st
import pandas as pd
import torch
import math
import re
import os

def set_seed(seed):
    torch.manual_seed(seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed_all(seed)
set_seed(1212)

def loadEnModel():
    os.system("python3 -m spacy download en_core_web_sm")
    st.session_state['models_loaded'] = True

class GramformerDemo:

    def __init__(self):
        if 'gf' not in st.session_state:
            st.session_state['gf'] = None

        st.set_page_config(
            page_title="Gramformer Demo",
            initial_sidebar_state="expanded",
            layout="wide"
            )
        self.model_map = {
            'Corrector': 1,
            'Detector - coming soon': 2
            }
        self.examples = [
            "what be the reason for everyone leave the comapny",
            "He are moving here.",
            "I am doing fine. How is you?",
            "How is they?",
            "Matt like fish",
            "the collection of letters was original used by the ancient Romans",
            "We enjoys horror movies",
            "Anna and Mike is going skiing",
            "I walk to the store and I bought milk",
            " We all eat the fish and then made dessert",
            "I will eat fish for dinner and drink milk",
            ]

    @st.cache(show_spinner=False, suppress_st_warning=True, allow_output_mutation=True)
    def load_gf(self, model: int):
        """

            Load Gramformer model

        """
        gf = Gramformer(models=model, use_gpu=False)
        return gf
    
    def show_highlights(self, gf: object, input_text: str, corrected_sentence: str):
        """

            To show highlights

        """
        try:
            strikeout = lambda x: '\u0336'.join(x) + '\u0336'
            highlight_text = gf.highlight(input_text, corrected_sentence)
            color_map = {'d':'#faa', 'a':'#afa', 'c':'#fea'}
            tokens = re.split(r'(<[dac]\s.*?<\/[dac]>)', highlight_text)
            annotations = []
            for token in tokens:
                soup = BeautifulSoup(token, 'html.parser')
                tags = soup.findAll()
                if tags:
                    _tag = tags[0].name
                    _type = tags[0]['type']
                    _text = tags[0]['edit']
                    _color = color_map[_tag]

                    if _tag == 'd':
                        _text = strikeout(tags[0].text)

                    annotations.append((_text, _type, _color))
                else:
                    annotations.append(token)
            annotated_text(*annotations)
        except Exception as e:
            print(e)
            st.error('Some error occured!')
            st.stop()
    
    def show_edits(self, gf: object, input_text: str, corrected_sentence: str):
        """

            To show edits

        """
        try:
            edits = gf.get_edits(input_text, corrected_sentence)
            df = pd.DataFrame(edits, columns=['type','original word', 'original start', 'original end', 'correct word', 'correct start', 'correct end'])
            df = df.set_index('type')
            st.table(df)
        except Exception as e:
            st.error('Some error occured!')
            st.stop()
    
    def main(self):
        github_repo = 'https://github.com/PrithivirajDamodaran/Gramformer'
        st.title("Gramformer - Concac")
        st.write(f'GitHub Link - [{github_repo}]({github_repo})')
        st.markdown('A framework for detecting, highlighting and correcting grammatical errors on natural language text')

        model_type = st.sidebar.selectbox(
            label='Choose Model',
            options=list(self.model_map.keys())
            )
        if model_type == 'Corrector':
            max_candidates = st.sidebar.number_input(
                label='Max candidates',
                min_value=1,
                max_value=10,
                value=1
                )
        else:
            # NOTE: 
            st.warning('TO BE IMPLEMENTED !!')
            st.stop()

        if not st.session_state['gf']:
            with st.spinner('Loading model..'):
                loadEnModel()
                gf = self.load_gf(self.model_map[model_type])
                st.session_state['gf'] = gf
        else:
            gf = st.session_state['gf']
    
        input_text = st.selectbox(
            label="Choose an example",
            options=self.examples
            )
        input_text = st.text_input(
            label="Input text",
            value=input_text
        )

        if input_text.strip():
            results = gf.correct(input_text, max_candidates=max_candidates)

            st.markdown(f'#### Output:')
            for i in range(0, len(results)):
                corrected_sentence, score = results[i]

                st.write('')
                st.markdown(f'###### # Candidate {i + 1}:')
                st.success(corrected_sentence)
                exp1 = st.expander(label='Show highlights', expanded=True)
                with exp1:
                    self.show_highlights(gf, input_text, corrected_sentence)
                exp2 = st.expander(label='Show edits')
                with exp2:
                    self.show_edits(gf, input_text, corrected_sentence)

        else:
            st.warning("Please select/enter text to proceed")
        
if __name__ == "__main__":
    obj = GramformerDemo()
    obj.main()