### Installation Source: https://github.com/kakaobrain/pororo/blob/master/docs/source/notes/intro.md Instructions for installing Pororo using conda or pip, and for local installation from source. ```APIDOC ## Installation ### Description Instructions for installing Pororo using conda or pip, and for local installation from source. ### Conda Installation ```bash # pororo only supports python>=3.6 conda create -n pororo python=3.6 conda activate pororo ``` ### Pip Installation ```bash pip install pororo ``` ### Local Installation ```bash git clone https://github.com/kakaobrain/pororo.git cd pororo pip install -e . ``` ### Additional Dependencies Since `Pororo` sets **English** as a default language option, you should follow [INSTALL](https://github.kakaocorp.com/kakaobrain/pororo/blob/master/INSTALL.md) guide to install other dependency libraries. ``` -------------------------------- ### Initialize and Use Image Captioning with PORORO Source: https://github.com/kakaobrain/pororo/blob/master/docs/_modules/pororo/tasks/image_captioning.html Demonstrates how to instantiate the captioning task using the Pororo factory and generate a description for a given image URL. ```python from pororo import Pororo caption = Pororo(task="caption", lang="en") result = caption("https://i.pinimg.com/originals/b9/de/80/b9de803706fb2f7365e06e688b7cc470.jpg") print(result) ``` -------------------------------- ### Install PORORO Library Source: https://context7.com/kakaobrain/pororo/llms.txt Instructions for installing the PORORO library via pip or from the source repository. ```bash pip install pororo git clone https://github.com/kakaobrain/pororo.git cd pororo pip install -e . ``` -------------------------------- ### Initialize and Configure PororoKoBartQuestionGeneration Source: https://github.com/kakaobrain/pororo/blob/master/docs/_modules/pororo/tasks/question_generation.html Demonstrates how to initialize the PororoKoBartQuestionGeneration class by loading necessary models like Wikipedia2Vec and KoBART, and setting up tokenization. ```python model = Wikipedia2Vec(model_file=f_wikipedia2vec, device=device) idx = index.open_dir(f_index) sim_words = SimilarWords(model, idx) model_path = download_or_load(f"bart/{self.config.n_model}", self.config.lang) model = KoBartModel.from_pretrained(device=device, model_path=model_path) sent_tok = (lambda text: PororoTokenizationFactory(task="tokenization", lang=self.config.lang, model=f"sent_{self.config.lang}").load(device).predict(text)) return PororoKoBartQuestionGeneration(model, sim_words, sent_tok, self.config) ``` -------------------------------- ### Python Usage Example Source: https://github.com/kakaobrain/pororo/blob/master/docs/_build/html/text_cls/para_id.html Example of how to use the Paraphrase Identification model in Python using the PORORO library. ```APIDOC ## Python Usage ### Description This code snippet demonstrates how to initialize and use the `PororoParaIdFactory` for paraphrase identification in Python. ### Method Python Class Instantiation and Method Call ### Endpoint N/A (Local execution) ### Parameters #### Class Initialization - **task** (str) - Set to 'paraphrase_identification'. - **lang** (str) - Set to 'ko' for Korean. - **model** (Optional[str]) - Specifies the model to use, e.g., 'brainbert.base.ko.paws'. #### Input Sentences - **sentence1** (str) - The first sentence for comparison. - **sentence2** (str) - The second sentence for comparison. ### Request Example ```python from pororo import Pororo # Initialize the paraphrase identification model for Korean paws = Pororo(task="paraphrase_identification", lang="ko", model="brainbert.base.ko.paws") # Example 1: Paraphrase sentence1 = "그는 빨간 자전거를 샀다" sentence2 = "그가 산 자전거는 빨간색이다." result1 = paws(sentence1, sentence2) print(f'Result 1: {result1}') # Example 2: Not Paraphrase sentence3 = "그는 빨간 자전거를 샀다" sentence4 = "그가 타고 있는 자전거는 빨간색이다." result2 = paws(sentence3, sentence4) print(f'Result 2: {result2}') ``` ### Response #### Success Response (Output) - **result1** (str) - 'Paraphrase' - **result2** (str) - 'NOT Paraphrase' #### Response Example ``` Result 1: Paraphrase Result 2: NOT Paraphrase ``` ``` -------------------------------- ### Initialize and Use Pororo G2P Source: https://github.com/kakaobrain/pororo/blob/master/examples/grapheme_to_phoneme.ipynb Demonstrates how to import the Pororo library, initialize the G2P task for a specific language, and perform phoneme conversion on input strings. ```python from pororo import Pororo # Korean G2P g2p_ko = Pororo(task="g2p", lang="ko") print(g2p_ko("어제는 날씨가 맑았는데, 오늘은 흐리다.")) print(g2p_ko("어제는 날씨가 맑았는데, 오늘은 흐리다.", align=True)) # English G2P g2p_en = Pororo(task="g2p", lang="en") print(g2p_en("I have $250 in my pocket.")) # Chinese G2P g2p_zh = Pororo(task="g2p", lang="zh") print(g2p_zh("然而,他红了20年以后,他竟退出了大家的视线。", align=True, tone=False)) # Japanese G2P g2p_ja = Pororo(task="g2p", lang="ja") print(g2p_ja("pythonが大好きです", align=True)) ``` -------------------------------- ### Initialize and Use Pororo Tokenization Source: https://github.com/kakaobrain/pororo/blob/master/docs/_build/html/_modules/pororo/tasks/tokenization.html Demonstrates how to instantiate the Pororo tokenization factory for specific languages and models, and how to tokenize input strings. ```python from pororo import Pororo # Korean tokenization with BPE tk_ko = Pororo(task="tokenization", lang="ko", model="bpe32k.ko") print(tk_ko("하늘을 나는 새를 보았다")) # English tokenization with RoBERTa tk_en = Pororo(task="tokenization", lang="en", model="roberta") print(tk_en("I love you")) ``` -------------------------------- ### Install Optical Character Recognition Dependencies Source: https://github.com/kakaobrain/pororo/blob/master/INSTALL.md Commands to install system-level and Python libraries required for OCR functionality. ```bash apt-get install -y libgl1-mesa-glx pip install opencv-python scikit-image ``` -------------------------------- ### Initialize PORORO Factory Class Source: https://context7.com/kakaobrain/pororo/llms.txt Demonstrates how to list available tasks and models, and instantiate a specific task model using the Pororo factory. ```python from pororo import Pororo # List all available tasks print(Pororo.available_tasks()) # Check available models for a specific task print(Pororo.available_models("ner")) # Instantiate a task model ner = Pororo(task="ner", lang="en") print(ner) ``` -------------------------------- ### Install PORORO Environment Source: https://github.com/kakaobrain/pororo/blob/master/docs/_build/html/notes/intro.html Commands to create a conda environment and install the PORORO library via pip or local source. ```bash conda create -n pororo python=3.6 conda activate pororo pip install pororo # Or local installation git clone https://github.com/kakaobrain/pororo.git cd pororo pip install -e . ``` -------------------------------- ### Initialize and Execute POS Tagging with Pororo Source: https://github.com/kakaobrain/pororo/blob/master/examples/pos_tagging.ipynb Demonstrates how to import the Pororo library, initialize the POS tagging task for a specific language, and process input strings to obtain tagged results. ```python from pororo import Pororo # Korean POS tagging pos_ko = Pororo(task="pos", lang="ko") print(pos_ko("95가지 알고리즘 문제 풀이로 완성하는 코딩 테스트")) # English POS tagging pos_en = Pororo(task="pos", lang="en") print(pos_en("The striped bats are hanging, on their feet for best.")) # Japanese POS tagging pos_ja = Pororo(task="pos", lang="ja") print(pos_ja("日本語でペラペラではないです")) # Chinese POS tagging pos_zh = Pororo(task="pos", lang="zh") print(pos_zh("乒乓球拍卖完了")) ``` -------------------------------- ### Install Chinese Language Task Dependencies Source: https://github.com/kakaobrain/pororo/blob/master/INSTALL.md Commands to install libraries required for Chinese grapheme-to-phoneme and PoS tagging tasks. ```bash pip install g2pM pip install jieba ``` -------------------------------- ### Initialize and Predict with PororoKoBartSummary Source: https://github.com/kakaobrain/pororo/blob/master/docs/_modules/pororo/tasks/text_summarization.html Demonstrates the initialization and prediction workflow for the KoBART-based abstractive summarizer. It uses beam search and sampling parameters to generate summaries from input text. ```python class PororoKoBartSummary(PororoGenerationBase): def __init__(self, model, config): super(PororoKoBartSummary, self).__init__(config) self._model = model @torch.no_grad() def predict(self, text: Union[str, List[str]], beam: int = 5, temperature: float = 1.0, top_k: int = -1, top_p: float = -1, no_repeat_ngram_size: int = 4, len_penalty: float = 1.0, **kwargs): sampling = (top_k != -1 or top_p != -1) output = self._model.translate(text, beam=beam, sampling=sampling, temperature=temperature, sampling_topk=top_k, sampling_topp=top_p, max_len_a=1, max_len_b=50, no_repeat_ngram_size=no_repeat_ngram_size, length_penalty=len_penalty) return output ``` -------------------------------- ### Install Japanese Language Task Dependencies Source: https://github.com/kakaobrain/pororo/blob/master/INSTALL.md Commands to install libraries required for Japanese RoBERTa, PoS tagging, and grapheme-to-phoneme conversion. ```bash pip install fugashi ipadic pip install romkan ``` -------------------------------- ### Install Automatic Speech Recognition Module Source: https://github.com/kakaobrain/pororo/blob/master/INSTALL.md Executes the installation script for the wav2letter dependency required for ASR tasks. Requires pre-installed CUDA. ```bash bash asr-install.sh ``` -------------------------------- ### Initialize and Use Tokenizer with PORORO Source: https://github.com/kakaobrain/pororo/blob/master/docs/_build/html/miscs/tokenization.html Demonstrates how to instantiate a tokenizer using the Pororo factory and process sentences into token lists. Supports multiple languages and specific model configurations. ```python from pororo import Pororo # Korean tokenization using bpe32k model tk_ko = Pororo(task="tokenization", lang="ko", model="bpe32k.ko") print(tk_ko("하늘을 나는 새를 보았다")) # English tokenization using roberta model tk_en = Pororo(task="tokenization", lang="en", model="roberta") print(tk_en("I love you")) ``` -------------------------------- ### Install Korean Language Task Dependencies Source: https://github.com/kakaobrain/pororo/blob/master/INSTALL.md Commands to install specific libraries for Korean tokenization, collocation, morphological inflection, and grapheme-to-phoneme tasks. ```bash pip install python-mecab-ko==1.0.9 pip install kollocate pip install koparadigm pip install g2pk ``` -------------------------------- ### Initialize and Use Lemmatization with PORORO Source: https://github.com/kakaobrain/pororo/blob/master/docs/_build/html/_modules/pororo/tasks/lemmatization.html Demonstrates how to instantiate the lemmatization task using the Pororo factory and apply it to a sentence to retrieve a list of lemmas. ```python from pororo import Pororo # Initialize the lemmatization task for English lemma = Pororo(task="lemma", lang="en") # Perform lemmatization on a sample sentence result = lemma("The striped bats are hanging, on their feet for best.") print(result) ``` -------------------------------- ### Initializing and Running NLP Tasks Source: https://github.com/kakaobrain/pororo/blob/master/README.md Shows how to instantiate a Pororo task object by specifying the task and language, and how to perform inference on input text. ```python from pororo import Pororo # Initialize NER task for English ner = Pororo(task="ner", lang="en") # Run inference ner("Michael Jeffrey Jordan is an American businessman.") # Initialize NER task for Korean ner_ko = Pororo(task="ner", lang="ko") ner_ko("마이클 제프리 조던은 미국의 농구 선수이다.") ``` -------------------------------- ### Text Summarization Examples Source: https://github.com/kakaobrain/pororo/blob/master/examples/text_summarization.ipynb Examples of text summarization using pretrained transformer models. Pororo supports 3 different types of summarization. ```APIDOC ## Abstractive Summarization ### Description Model generates a summary in the form of a complete sentence. ### Method ```python from pororo import Pororo abs_summ = Pororo(task="text_summarization", lang="ko", model="abstractive") ``` ### Endpoint N/A (This is a Python library function) ### Parameters - **input_text** (str or list[str]) - Required - The text or list of texts to summarize. - **beam** (int) - Optional - Beam width for beam search decoding. - **len_penalty** (float) - Optional - Length penalty for beam search. - **no_repeat_ngram_size** (int) - Optional - If set, suppresses generating n-grams that have already appeared. - **top_k** (int) - Optional - Top-k sampling parameter. - **top_p** (float) - Optional - Top-p (nucleus) sampling parameter. - **return_list** (bool) - Optional - If True, returns summaries as a list of strings. If False (default), returns a single string for single input or list of strings for batch input. ### Request Example ```python input_text1 = "가수 김태연은 걸 그룹 소녀시대, 소녀시대-태티서 및 소녀시대-Oh!GG의 리더이자 메인보컬이다. 2004년 SM에서 주최한 청소년 베스트 선발 대회에서 노래짱 대상을 수상하며 SM 엔터테인먼트에 캐스팅되었다. 이후 3년간의 연습생을 거쳐 2007년 소녀시대의 멤버로 데뷔했다. 태연은 1989년 3월 9일 대한민국 전라북도 전주시 완산구에서 아버지 김종구, 어머니 김희자 사이의 1남 2녀 중 둘째로 태어났다. 가족으로는 오빠 김지웅, 여동생 김하연이 있다. 어릴 적부터 춤을 좋아했고 특히 명절 때는 친척들이 춤을 시키면 곧잘 추었다던 태연은 TV에서 보아를 보고 가수의 꿈을 갖게 되었다고 한다. 전주양지초등학교를 졸업하였고 전주양지중학교 2학년이던 2003년 SM아카데미 스타라이트 메인지방보컬과 4기에 들어가게 되면서 아버지와 함께 주말마다 전주에서 서울로 이동하며 가수의 꿈을 키웠다. 2004년에 당시 보컬 트레이너였던 더 원의 정규 2집 수록곡 〈You Bring Me Joy (Part 2)〉에 피처링으로 참여했다. 당시 만 15세였던 태연은 현재 활동하는 소속사 SM 엔터테인먼트에 들어가기 전이었다. 이후 태연은 2004년 8월에 열린 제8회 SM 청소년 베스트 선발 대회에서 노래짱 부문에 출전해 1위(대상)를 수상하였고 SM 엔터테인먼트에 정식 캐스팅되어 연습생 생활을 시작하게 되었다. 2005년 청담고등학교에 입학하였으나, 학교 측에서 연예계 활동을 용인하지 않아 전주예술고등학교 방송문화예술과로 전학하였고 2008년 졸업하면서 학교를 빛낸 공로로 공로상을 수상했다. 태연은 연습생 생활이 힘들어 숙소에서 몰래 뛰쳐나갔다가 하루 만에 다시 돌아오기도 했다고 이야기하기도 했다. 이후 SM엔터테인먼트에서 3년여의 연습생 기간을 거쳐 걸 그룹 소녀시대의 멤버로 정식 데뷔하게 되었다." abs_summ(input_text1) # supports batchwise inference input_text2 = "목성과 토성이 약 400년 만에 가장 가까이 만났습니다. 국립과천과학관 등 천문학계에 따르면 21일 저녁 목성과 토성은 1623년 이후 397년 만에 가장 가까워졌는데요. 크리스마스 즈음까지 남서쪽 하늘을 올려다보면 목성과 토성이 가까워지는 현상을 관측할 수 있습니다. 목성의 공전주기는 11.9년, 토성의 공전주기는 29.5년인데요. 공전주기의 차이로 두 행성은 약 19.9년에 한 번 가까워집니다. 이번 근접 때 목성과 토성 사이 거리는 보름달 지름의 5분의 1 정도로 가까워졌습니다. 맨눈으로 보면 두 행성이 겹쳐져 하나의 별처럼 보이는데요. 지난 21일 이후 목성과 토성의 대근접은 2080년 3월 15일로 예측됩니다. 과천과학관 측은 우리가 대근접을 볼 수 있는 기회는 이번이 처음이자 마지막이 될 가능성이 크다라고 설명했 습니다." abs_summ([input_text1, input_text2]) # supports various decoding strategies abs_summ( input_text1, beam=5, len_penalty=0.6, no_repeat_ngram_size=3, top_k=50, top_p=0.7 ) ``` ### Response #### Success Response (200) - **summary** (str or list[str]) - The summarized text. ### Response Example ```json { "summary": "가수 태연은 2004년 SM 청소년 베스트 선발 대회에서 노래짱 대상을 수상하고 SM 엔터테인먼트에 캐스팅되어 3년간의 연습생 기간을 거쳐 2007년 소녀시대의 멤버로 데뷔했다." } ``` ``` ```APIDOC ## Extractive Summarization ### Description Model extracts a specified number of important sentences from an article. ### Method ```python ext_summ = Pororo(task="text_summarization", lang="ko", model="extractive") ``` ### Endpoint N/A (This is a Python library function) ### Parameters - **input_text** (str or list[str]) - Required - The text or list of texts to summarize. - **return_list** (bool) - Optional - If True, returns extracted summaries as a list of strings for each input text. If False (default), returns a single string concatenating the extracted sentences for each input text. ### Request Example ```python input_text1 = "가수 김태연은 걸 그룹 소녀시대, 소녀시대-태티서 및 소녀시대-Oh!GG의 리더이자 메인보컬이다. 2004년 SM에서 주최한 청소년 베스트 선발 대회에서 노래짱 대상을 수상하며 SM 엔터테인먼트에 캐스팅되었다. 이후 3년간의 연습생을 거쳐 2007년 소녀시대의 멤버로 데뷔했다. 태연은 1989년 3월 9일 대한민국 전라북도 전주시 완산구에서 아버지 김종구, 어머니 김희자 사이의 1남 2녀 중 둘째로 태어났다. 가족으로는 오빠 김지웅, 여동생 김하연이 있다. 어릴 적부터 춤을 좋아했고 특히 명절 때는 친척들이 춤을 시키면 곧잘 추었다던 태연은 TV에서 보아를 보고 가수의 꿈을 갖게 되었다고 한다. 전주양지초등학교를 졸업하였고 전주양지중학교 2학년이던 2003년 SM아카데미 스타라이트 메인지방보컬과 4기에 들어가게 되면서 아버지와 함께 주말마다 전주에서 서울로 이동하며 가수의 꿈을 키웠다. 2004년에 당시 보컬 트레이너였던 더 원의 정규 2집 수록곡 〈You Bring Me Joy (Part 2)〉에 피처링으로 참여했다. 당시 만 15세였던 태연은 현재 활동하는 소속사 SM 엔터테인먼트에 들어가기 전이었다. 이후 태연은 2004년 8월에 열린 제8회 SM 청소년 베스트 선발 대회에서 노래짱 부문에 출전해 1위(대상)를 수상하였고 SM 엔터테인먼트에 정식 캐스팅되어 연습생 생활을 시작하게 되었다. 2005년 청담고등학교에 입학하였으나, 학교 측에서 연예계 활동을 용인하지 않아 전주예술고등학교 방송문화예술과로 전학하였고 2008년 졸업하면서 학교를 빛낸 공로로 공로상을 수상했다. 태연은 연습생 생활이 힘들어 숙소에서 몰래 뛰쳐나갔다가 하루 만에 다시 돌아오기도 했다고 이야기하기도 했다. 이후 SM엔터테인먼트에서 3년여의 연습생 기간을 거쳐 걸 그룹 소녀시대의 멤버로 정식 데뷔하게 되었다." ext_summ(input_text1) # support batchwise inference input_text2 = "목성과 토성이 약 400년 만에 가장 가까이 만났습니다. 국립과천과학관 등 천문학계에 따르면 21일 저녁 목성과 토성은 1623년 이후 397년 만에 가장 가까워졌는데요. 크리스마스 즈음까지 남서쪽 하늘을 올려다보면 목성과 토성이 가까워지는 현상을 관측할 수 있습니다. 목성의 공전주기는 11.9년, 토성의 공전주기는 29.5년인데요. 공전주기의 차이로 두 행성은 약 19.9년에 한 번 가까워집니다. 이번 근접 때 목성과 토성 사이 거리는 보름달 지름의 5분의 1 정도로 가까워졌습니다. 맨눈으로 보면 두 행성이 겹쳐져 하나의 별처럼 보이는데요. 지난 21일 이후 목성과 토성의 대근접은 2080년 3월 15일로 예측됩니다. 과천과학관 측은 우리가 대근접을 볼 수 있는 기회는 이번이 처음이자 마지막이 될 가능성이 크다라고 설명했 습니다." ext_summ([input_text1, input_text2]) # set `retrun_list=True` to return extracted summaries as lists. ext_summ(input_text1, return_list=True) # support batchwise inference ext_summ([input_text1, input_text2], return_list=True) ``` ### Response #### Success Response (200) - **summary** (str or list[str]) - The extracted sentences as a summary. ### Response Example ```json { "summary": "2004년 SM에서 주최한 청소년 베스트 선발 대회에서 노래짱 대상을 수상하며 SM 엔터테인먼트에 캐스팅되었다. 이후 태연은 2004년 8월에 열린 제8회 SM 청소년 베스트 선발 대회에서 노래짱 부문에 출전해 1위(대상)를 수상하였고 SM 엔터테인먼트에 정식 캐스팅되어 연습생 생활을 시작하게 되었다. 이후 SM엔터테인먼트에서 3년여의 연습생 기간을 거쳐 걸 그룹 소녀시대의 멤버로 정식 데뷔하게 되었다." } ``` ``` ```APIDOC ## Bullet-point Summarization ### Description Model generates multiple summaries in the form of short phrases, similar to note handwritings and presentations. ### Method ```python bullet_summ = Pororo(task="text_summarization", lang="ko", model="bullet") ``` ### Endpoint N/A (This is a Python library function) ### Parameters - **input_text** (str or list[str]) - Required - The text or list of texts to summarize. - **return_list** (bool) - Optional - If True, returns summaries as a list of strings. If False (default), returns a single string for single input or list of strings for batch input. ### Request Example ```python input_text1 = "가수 김태연은 걸 그룹 소녀시대, 소녀시대-태티서 및 소녀시대-Oh!GG의 리더이자 메인보컬이다. 2004년 SM에서 주최한 청소년 베스트 선발 대회에서 노래짱 대상을 수상하며 SM 엔터테인먼트에 캐스팅되었다. 이후 3년간의 연습생을 거쳐 2007년 소녀시대의 멤버로 데뷔했다. 태연은 1989년 3월 9일 대한민국 전라북도 전주시 완산구에서 아버지 김종구, 어머니 김희자 사이의 1남 2녀 중 둘째로 태어났다. 가족으로는 오빠 김지웅, 여동생 김하연이 있다. 어릴 적부터 춤을 좋아했고 특히 명절 때는 친척들이 춤을 시키면 곧잘 추었다던 태연은 TV에서 보아를 보고 가수의 꿈을 갖게 되었다고 한다. 전주양지초등학교를 졸업하였고 전주양지중학교 2학년이던 2003년 SM아카데미 스타라이트 메인지방보컬과 4기에 들어가게 되면서 아버지와 함께 주말마다 전주에서 서울로 이동하며 가수의 꿈을 키웠다. 2004년에 당시 보컬 트레이너였던 더 원의 정규 2집 수록곡 〈You Bring Me Joy (Part 2)〉에 피처링으로 참여했다. 당시 만 15세였던 태연은 현재 활동하는 소속사 SM 엔터테인먼트에 들어가기 전이었다. 이후 태연은 2004년 8월에 열린 제8회 SM 청소년 베스트 선발 대회에서 노래짱 부문에 출전해 1위(대상)를 수상하였고 SM 엔터테인먼트에 정식 캐스팅되어 연습생 생활을 시작하게 되었다. 2005년 청담고등학교에 입학하였으나, 학교 측에서 연예계 활동을 용인하지 않아 전주예술고등학교 방송문화예술과로 전학하였고 2008년 졸업하면서 학교를 빛낸 공로로 공로상을 수상했다. 태연은 연습생 생활이 힘들어 숙소에서 몰래 뛰쳐나갔다가 하루 만에 다시 돌아오기도 했다고 이야기하기도 했다. 이후 SM엔터테인먼트에서 3년여의 연습생 기간을 거쳐 걸 그룹 소녀시대의 멤버로 정식 데뷔하게 되었다." bullet_summ(input_text1) ``` ### Response #### Success Response (200) - **summary** (str or list[str]) - The bullet-point summaries. ### Response Example ```json { "summary": "['태연, 2004년 청소년 베스트 선발 대회에서 노래짱 대상 수상', ' 태연, SM엔터테인먼트에서 3년여의 연습생 기간 거쳐 걸 그룹 소녀시대의 멤버로 정식 데뷔']" } ``` ``` -------------------------------- ### Install Pororo using Pip Source: https://github.com/kakaobrain/pororo/blob/master/docs/_build/html/_sources/notes/intro.md.txt Installs the Pororo library using pip. Ensure you have a compatible Python version (>=3.6) and a suitable environment set up. ```bash pip install pororo ``` -------------------------------- ### Initialize and Load ASR Models Source: https://github.com/kakaobrain/pororo/blob/master/docs/_modules/pororo/tasks/automatic_speech_recognition.html Demonstrates how to retrieve available languages and models, and load the specific ASR model using the PororoAsrFactory. ```python from pororo.tasks.automatic_speech_recognition import PororoAsrFactory # Get available languages and models langs = PororoAsrFactory.get_available_langs() models = PororoAsrFactory.get_available_models() # Load model for a specific device factory = PororoAsrFactory(task='asr', lang='en', model='wav2vec.en') asr_engine = factory.load(device='cpu') ``` -------------------------------- ### Install Pororo Locally Source: https://github.com/kakaobrain/pororo/blob/master/docs/_build/html/_sources/notes/intro.md.txt Installs Pororo locally by cloning the repository and using pip in editable mode. This method is useful for development or when needing the latest code. ```bash git clone https://github.com/kakaobrain/pororo.git cd pororo pip install -e . ``` -------------------------------- ### Initialize and Use Question Generation Source: https://github.com/kakaobrain/pororo/blob/master/docs/_modules/pororo/tasks/question_generation.html Demonstrates how to instantiate the question generation task using the Pororo factory and perform inference with context and answer inputs, including the generation of wrong answer candidates. ```python from pororo import Pororo # Initialize the question generation task for Korean qg = Pororo(task="qg", lang="ko") # Generate a question and 3 wrong answers based on the provided context result = qg( "카카오톡", "카카오톡은 스마트폰의 데이터 통신 기능을 이용하여, 문자 과금 없이 사람들과 메시지를 주고받을 수 있는 애플리케이션이다.", n_wrong=3 ) ``` -------------------------------- ### Initialize and Use PORORO Lemmatization Source: https://github.com/kakaobrain/pororo/blob/master/docs/_modules/pororo/tasks/lemmatization.html Demonstrates how to initialize the PORORO lemmatization task and apply it to an input sentence to retrieve a list of lemmas. ```python from pororo import Pororo lemma = Pororo(task="lemma", lang="en") result = lemma("The striped bats are hanging, on their feet for best.") print(result) ``` -------------------------------- ### Install Core Pororo Dependencies Source: https://github.com/kakaobrain/pororo/blob/master/INSTALL.md Lists the essential Python packages required for the base functionality of Pororo. These are typically handled automatically during standard pip installation. ```python requirements = [ "torch==1.6.0", "torchvision==0.7.0", "pillow>=4.1.1", "fairseq>=0.10.2", "transformers>=4.0.0", "sentence_transformers>=0.4.1.2", "nltk>=3.5", "word2word", "wget", "joblib", "lxml", "g2p_en", "whoosh", "marisa-trie", "kss", 'dataclasses; python_version<"3.7"', ] ``` -------------------------------- ### Initialize and Use WSD Task Source: https://github.com/kakaobrain/pororo/blob/master/docs/_modules/pororo/tasks/word_sense_disambiguation.html Demonstrates how to instantiate the WSD task using the Pororo factory and process a Korean sentence to retrieve disambiguated word senses. ```python from pororo import Pororo # Initialize the WSD task for Korean wsd = Pororo(task="wsd", lang="ko") # Perform disambiguation on a sample sentence result = wsd("머리에 이가 있나봐.") print(result) ``` -------------------------------- ### Get Available Models for Paraphrase Generation (Python) Source: https://github.com/kakaobrain/pororo/blob/master/docs/_build/html/_modules/pororo/tasks/paraphrase_generation.html Provides a way to get a dictionary of available paraphrase generation models, categorized by language. This helps in selecting the appropriate model for a specific language. ```python from pororo.tasks.paraphrase_generation import PororoParaphraseFactory print(PororoParaphraseFactory.get_available_models()) ``` -------------------------------- ### Initialize and Load GEC Models Source: https://github.com/kakaobrain/pororo/blob/master/docs/_build/html/_modules/pororo/tasks/grammatical_error_correction.html Demonstrates how to retrieve available languages and models, and the internal logic for loading specific model architectures like CharBERT or Transformer-based GEC. ```python @staticmethod def get_available_langs(): return ["en", "ko"] @staticmethod def get_available_models(): return { "en": ["transformer.base.en.gec", "transformer.base.en.char_gec"], "ko": ["charbert.base.ko.spacing"] } def load(self, device: str): if "charbert" in self.config.n_model: from pororo.models.brainbert import CharBrainRobertaModel model = (CharBrainRobertaModel.load_model(f"bert/{self.config.n_model}", self.config.lang).eval().to(device)) return PororoBertSpacing(model, self.config) if "transformer" in self.config.n_model: from fairseq.models.transformer import TransformerModel load_dict = download_or_load(f"transformer/{self.config.n_model}", self.config.lang) model = (TransformerModel.from_pretrained(model_name_or_path=load_dict.path, checkpoint_file=f"{self.config.n_model}.pt", data_name_or_path=load_dict.dict_path, source_lang=load_dict.src_dict, target_lang=load_dict.tgt_dict).eval().to(device)) return PororoTransformerGecChar(model, self.config) if "char" in self.config.n_model else PororoTransformerGec(model, tokenizer, device, self.config) ``` -------------------------------- ### GET /pororo/collocation/models Source: https://github.com/kakaobrain/pororo/blob/master/docs/_build/html/miscs/collocation.html Retrieves a list of all available collocation models. ```APIDOC ## GET /pororo/collocation/models ### Description Returns a list of available models for the collocation task. ### Method GET ### Endpoint /pororo/collocation/models ### Response #### Success Response (200) - **models** (list) - A list of available model names. #### Response Example { "models": ["collocation.base", "collocation.large"] } ``` -------------------------------- ### PORORO OCR Initialization and Usage (Python) Source: https://github.com/kakaobrain/pororo/blob/master/docs/miscs/ocr.html Demonstrates how to initialize the PORORO OCR model for Korean language and perform OCR on an image. It shows both basic text extraction and detailed output with bounding polygons. ```python from pororo import Pororo # Initialize OCR for Korean language ocr = Pororo(task="ocr", lang="ko") # Perform OCR on an image (basic output) result_basic = ocr(IMAGE_PATH) print(result_basic) # Perform OCR on an image (detailed output with bounding polygons) result_detailed = ocr(IMAGE_PATH, detail=True) print(result_detailed) ``` -------------------------------- ### GET /models/available Source: https://github.com/kakaobrain/pororo/blob/master/docs/seq2seq/const.html Retrieve a list of available constituency parsing models. ```APIDOC ## GET /models/available ### Description Returns a list of available models for the constituency parsing task. ### Method GET ### Endpoint /models/available ### Response #### Success Response (200) - **models** (list) - A list of strings representing available model names. ``` -------------------------------- ### GET /word2vec/vector Source: https://github.com/kakaobrain/pororo/blob/master/docs/_modules/pororo/tasks/word_embedding.html Retrieves the vector representation for a given word or entity. ```APIDOC ## GET /word2vec/vector ### Description Retrieves the vector representation for a specified word or entity. This returns an OrderedDict containing the word/entity and its corresponding tensor representation. ### Method GET ### Endpoint /word2vec/vector ### Parameters #### Query Parameters - **word** (string) - Required - The word or entity to search for. - **lang** (string) - Optional - The language code (e.g., 'en', 'ko'). ### Request Example { "word": "apple", "lang": "en" } ### Response #### Success Response (200) - **result** (OrderedDict) - A mapping of word/entity variants to their respective tensor embeddings. #### Response Example { "apple (word)": "tensor([...])", "Apple (fruit)": "tensor([...])" } ``` -------------------------------- ### Initialize and Execute Dependency Parsing Source: https://github.com/kakaobrain/pororo/blob/master/docs/_build/html/tagging/dp.html Demonstrates how to instantiate the dependency parser using the Pororo factory and perform syntactic analysis on Korean sentences. The output returns a list of tuples containing token index, text, head index, and dependency relation. ```python from pororo import Pororo # Initialize the dependency parser for Korean dp = Pororo(task="dep_parse", lang="ko") # Perform dependency parsing on a sentence result = dp("분위기도 좋고 음식도 맛있었어요. 한 시간 기다렸어요.") print(result) # Example with a shorter sentence result_short = dp("한시간 기다렸어요.") print(result_short) ``` -------------------------------- ### Initialize and Use Pororo Question Generation Source: https://github.com/kakaobrain/pororo/blob/master/docs/_build/html/_modules/pororo/tasks/question_generation.html Demonstrates how to initialize the question generation task in PORORO and generate a question along with wrong answer candidates based on a provided answer and context. ```python from pororo import Pororo # Initialize the question generation task for Korean qg = Pororo(task="qg", lang="ko") # Generate a question and 3 wrong answers result = qg( "카카오톡", "카카오톡은 스마트폰의 데이터 통신 기능을 이용하여, 문자 과금 없이 사람들과 메시지를 주고받을 수 있는 애플리케이션이다.", n_wrong=3 ) ``` -------------------------------- ### GET /asr/models Source: https://github.com/kakaobrain/pororo/blob/master/docs/miscs/asr.html Retrieves available languages and models for the ASR task. ```APIDOC ## GET /asr/models ### Description Fetches the list of available languages and models supported by the ASR factory. ### Method GET ### Endpoint /asr/models ### Response #### Success Response (200) - **models** (list) - A list of available model identifiers. ``` -------------------------------- ### Initialize and execute ASR with Pororo Source: https://github.com/kakaobrain/pororo/blob/master/examples/automatic_speech_recognition.ipynb This snippet shows how to import the Pororo library, initialize the ASR task for a specific language, and transcribe an audio file. It supports various formats including WAV, FLAC, MP3, and PCM. ```python from pororo import Pororo # Initialize ASR for English asr_en = Pororo(task="asr", lang="en") print(asr_en('english.wav')) # Initialize ASR for Korean asr_ko = Pororo(task="asr", lang="ko") print(asr_ko('korean.wav')) ```