|
| 1 | +import json |
| 2 | + |
| 3 | +import requests |
| 4 | + |
| 5 | + |
| 6 | +class RtzrAPI: |
| 7 | + def __init__( |
| 8 | + self, |
| 9 | + client_id: str, |
| 10 | + client_sceret: str, |
| 11 | + dev: bool, |
| 12 | + file_path: dict, |
| 13 | + speaker_num: int, |
| 14 | + domain: str, |
| 15 | + profanity_filter: bool, |
| 16 | + keyword: list, |
| 17 | + summary_model, |
| 18 | + summary_tokenizer, |
| 19 | + ) -> None: |
| 20 | + """api 사용에 필요한 인자 초기화""" |
| 21 | + self.dev: str = "dev-" if dev else "" |
| 22 | + self.client_id: str = client_id |
| 23 | + self.client_sceret: str = client_sceret |
| 24 | + self.file_path: dict = file_path |
| 25 | + self.speaker_num: int = speaker_num |
| 26 | + self.config: dict = {"domain": "GENERAL"} if domain == "일반" else {"domain": "CALL"} |
| 27 | + |
| 28 | + if speaker_num != 0: |
| 29 | + self.config["use_diarization"] = True |
| 30 | + self.config["diarization"] = {"spk_count": speaker_num} |
| 31 | + if profanity_filter: |
| 32 | + self.config["use_profanity_filter"] = True |
| 33 | + if keyword: |
| 34 | + self.config["keyword"] = keyword |
| 35 | + |
| 36 | + self.model = summary_model |
| 37 | + self.tokenizer = summary_tokenizer |
| 38 | + |
| 39 | + self.raw_data: json = None |
| 40 | + self.voice_data: str = None |
| 41 | + self.summary_data: str = None |
| 42 | + self.access_token: str = self.auth_check(client_id, client_sceret) |
| 43 | + self.transcribe_id: str = self.api_post(self.access_token) |
| 44 | + |
| 45 | + def auth_check(self, client_id: str, client_sceret: str) -> str: |
| 46 | + """client id와 client sceret을 인자로 받고 api요청에 필요한 access token을 리턴하는 메소드""" |
| 47 | + resp = requests.post( |
| 48 | + f"https://{self.dev}openapi.vito.ai/v1/authenticate", |
| 49 | + data={"client_id": client_id, "client_secret": client_sceret}, |
| 50 | + ) |
| 51 | + |
| 52 | + resp.raise_for_status() |
| 53 | + return resp.json()["access_token"] |
| 54 | + |
| 55 | + def api_post(self, access_token: str) -> None: |
| 56 | + """access_token을 인자로 받고 api요청을 하는 함수. Get에 필요한 transcribe_id 리턴하는 메소드""" |
| 57 | + resp = requests.post( |
| 58 | + f"https://{self.dev}openapi.vito.ai/v1/transcribe", |
| 59 | + headers={"Authorization": f"Bearer {access_token}"}, |
| 60 | + files=self.file_path, |
| 61 | + data={"config": json.dumps(self.config)}, |
| 62 | + ) |
| 63 | + |
| 64 | + resp.raise_for_status() |
| 65 | + return resp.json()["id"] |
| 66 | + |
| 67 | + def api_get( |
| 68 | + self, |
| 69 | + ) -> None: |
| 70 | + """텍스트로 변환된 값을 받는 메소드""" |
| 71 | + resp = requests.get( |
| 72 | + f"https://{self.dev}openapi.vito.ai/v1/transcribe/" + self.transcribe_id, |
| 73 | + headers={"Authorization": "bearer " + self.access_token}, |
| 74 | + ) |
| 75 | + resp.raise_for_status() |
| 76 | + if resp.json()["status"] == "transcribing": |
| 77 | + self.raw_data = None |
| 78 | + else: |
| 79 | + self.raw_data = resp.json() |
| 80 | + self.voice_data = self.preprocessing(self.raw_data) |
| 81 | + |
| 82 | + def preprocessing(self, raw_data: dict) -> str: |
| 83 | + """ |
| 84 | + 텍스트를 전처리 하는 메소드 |
| 85 | + 화자가 두 명 이상일 경우 speaker n] text... 형태로 출력 |
| 86 | + """ |
| 87 | + if len(set([x["spk"] for x in raw_data["results"]["utterances"]])) == 1: |
| 88 | + return " ".join([data["msg"] for data in raw_data["results"]["utterances"]]) |
| 89 | + else: |
| 90 | + return " \n".join( |
| 91 | + [f"화자{text_data['spk']} ] {text_data['msg']}" for text_data in raw_data["results"]["utterances"]] |
| 92 | + ) |
| 93 | + |
| 94 | + def summary_inference( |
| 95 | + self, |
| 96 | + ) -> None: |
| 97 | + """hugging face 모델을 사용해 텍스트 내용을 요약해주는 함수. 문장이 짧으면 'Text too short를 반환""" |
| 98 | + |
| 99 | + # short data handling |
| 100 | + if len(self.voice_data) < 40: |
| 101 | + self.summary_data = "Text too short!!" |
| 102 | + return None |
| 103 | + |
| 104 | + # Encoding |
| 105 | + inputs = self.tokenizer( |
| 106 | + self.voice_data, |
| 107 | + return_tensors="pt", |
| 108 | + padding="max_length", |
| 109 | + truncation=True, |
| 110 | + max_length=1026, |
| 111 | + ) |
| 112 | + |
| 113 | + # Generate Summary Text |
| 114 | + summary_text_ids = self.model.generate( |
| 115 | + input_ids=inputs["input_ids"], |
| 116 | + attention_mask=inputs["attention_mask"], |
| 117 | + bos_token_id=self.model.config.bos_token_id, |
| 118 | + eos_token_id=self.model.config.eos_token_id, |
| 119 | + length_penalty=1.0, |
| 120 | + max_length=300, |
| 121 | + min_length=12, |
| 122 | + num_beams=6, |
| 123 | + repetition_penalty=1.5, |
| 124 | + no_repeat_ngram_size=15, |
| 125 | + ) |
| 126 | + |
| 127 | + # Decoding |
| 128 | + self.summary_data = self.tokenizer.decode(summary_text_ids[0], skip_special_tokens=True) |
| 129 | + |
| 130 | + def get_raw_data(self) -> dict: |
| 131 | + """api를 통해 얻은 원시 데이터 반환""" |
| 132 | + return self.raw_data |
| 133 | + |
| 134 | + def get_text_data(self) -> str: |
| 135 | + """텍스트로 변환된 데이터 반환""" |
| 136 | + return self.voice_data |
| 137 | + |
| 138 | + def get_summary_data(self) -> str: |
| 139 | + """텍스트가 요약된 데이터 반환""" |
| 140 | + return self.summary_data |
0 commit comments