Spaces:
Runtime error
Runtime error
File size: 3,717 Bytes
de0cb94 20cd76d de0cb94 c9ac1af de0cb94 c9ac1af 20cd76d c9ac1af de0cb94 20cd76d de0cb94 |
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 |
import hashlib
import logging
import os
from datetime import datetime
from typing import Dict, Any, List
import gradio as gr
import spacy
from pony.orm import db_session
from spacy import displacy
from core.classificator import Classificator, Classification
from core.models.request import Request
from settings import db
class Application:
examples = [
'Things are complicated because we still live together but we have separate lives',
'My dad is a monster and took his anger out on my mom by verbally abusing her and when she left he '
'eventually moved on to my brother',
'A two months ago, she was chatting with some random guy',
'Not I have a horrid relationship with my brother we’ve never gotten along and probably never will',
'I was outside trying to leave and he caught me to explain why Im so rude',
]
def __init__(self, classificator: Classificator, options: Dict[str, Any]):
self.options = options
self.classificator = classificator
self.nlp = spacy.load("en_core_web_md")
def handle(self, input_text: str) -> str:
"""
Handle the input text and return the result as rendered html
"""
if input_text is None or input_text == '':
return ''
classifications = self.classificator.classify(input_text)
request = self.log_request(input_text, classifications)
# TODO: тут надо взять хеш или ид, прокинуть его для формирования кнопок с оценкой
return self.render(input_text, classifications)
@staticmethod
@db_session
def log_request(input_text: str, classifications: List[Classification]) -> Request:
"""
Log the request to the database
"""
return Request(
text=input_text,
hash=hashlib.md5(input_text.encode()).hexdigest(),
created_at=datetime.now(),
updated_at=datetime.now(),
rating=0,
result=[c.dict() for c in classifications]
)
def render(self, input_text: str, classifications: List[Classification]) -> str:
"""
Render the input text and the classifications as html text with labels
"""
document = self.nlp(input_text)
try:
document.ents = [
document.char_span(classification.start, classification.end, classification.entity) for
classification in classifications
]
except Exception as exc:
logging.exception(exc)
return displacy.render(document, style="ent", options=self.options)
def run(self):
iface = gr.Interface(
fn=self.handle, inputs=gr.Textbox(
lines=5, placeholder="Enter your text here",
label='Check your text for compliance with the NVC rules'),
outputs=["html"], examples=self.examples
)
iface.launch()
if __name__ == '__main__':
db.bind(
provider='postgres',
user=os.getenv('pg_user'),
password=os.getenv('pg_password'),
host=os.getenv('pg_host'),
port=os.getenv('pg_port'),
database=os.getenv('pg_database')
)
db.generate_mapping(create_tables=True)
application = Application(
classificator=Classificator(
config={
'auth_endpoint_token': os.getenv("auth_endpoint_token"),
'endpoint_url': os.getenv("endpoint_url")
}
),
options={"ents": ["Observation", "Evaluation"], "colors": {"Observation": "#9bddff", "Evaluation": "#f08080"}}
)
application.run()
|