import gradio as gr import model_wrapper model = model_wrapper.PredictionModel() def pretty_print_opinion(opinion_dict): res = [] maxlen = max([len(key) for key in opinion_dict.keys()]) + 2 maxlen = 0 for key, value in opinion_dict.items(): if key == 'Polarity': res.append(f'{(key + ":").ljust(maxlen)} {value}') else: res.append(f'{(key + ":").ljust(maxlen)} \'{" ".join(value[0])}\'') return '\n'.join(res) + '\n' def predict(text): print(f'Input message "{text}"') try: predictions = model.predict([text]) prediction = predictions[0] results = [] if not prediction['opinions']: return 'No opinions detected' for opinion in prediction['opinions']: results.append(pretty_print_opinion(opinion)) print(f'Successfully predicted SA for input message "{text}": {results}') return '\n'.join(results) except Exception as e: print(f'Error for input message "{text}": {e}') raise e markdown_text = '''
This space provides a gradio demo of a [pretrained model](https://huggingface.co/ltg/ssa-perin) (with an easy-to-run wrapper) for structured sentiment analysis (SSA) of Norwegian text, trained on the [NoReC_fine](https://github.com/ltgoslo/norec_fine) dataset. It implements a method described in the paper [Direct parsing to sentiment graphs](https://aclanthology.org/2022.acl-short.51/) by Samuel et al. 2022. The model will attempt to identify the following components for a given sentence it deems to be sentiment-bearing: _source expressions_ (the opinion holder), _target expressions_ (what the opinion is directed towards), _polar expressions_ (the part of the text indicating that an opinion is expressed), and finally the _polarity_ (positive or negative). See the code below for an example of how you can use the model yourself for predicting such sentiment tuples (along with character offsets in the text): ```python >>> import model_wrapper >>> model = model_wrapper.PredictionModel() >>> model.predict(['vi liker svart kaffe']) [{'sent_id': '0', 'text': 'vi liker svart kaffe', 'opinions': [{'Source': [['vi'], ['0:2']], 'Target': [['svart', 'kaffe'], ['9:14', '15:20']], 'Polar_expression': [['liker'], ['3:8']], 'Polarity': 'Positive'}]}] ``` To download the model and find more in-depth documentation, please see (https://huggingface.co/ltg/ssa-perin)[https://huggingface.co/ltg/ssa-perin] ''' with gr.Blocks() as demo: with gr.Row() as row: text_input = gr.Textbox(label="input") text_output = gr.Textbox(label="output") with gr.Row() as row: text_button = gr.Button("submit") text_button.click(fn=predict, inputs=text_input, outputs=text_output) gr.Markdown(markdown_text) demo.launch()