Giter VIP home page Giter VIP logo

korpora's People

Contributors

hank110 avatar hungry-wook avatar hwiorn avatar lovit avatar ratsgo avatar warnikchow avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

korpora's Issues

Make KorpusData as Iterable

usage scenario

from Korpora import NSMC

nsmc  = NSMC()
for text, label in nsmc:
    print(type(text))  # str
    print(type(label))  # int

질문쌍 데이터

question1	question2	is_duplicate
밤만 되면 미치겟네.	밥먹기 참 힘드네	1
나 같이 헤어진 경우도 있을까?	나 잘하는 거 맞을까?	1
매일 아침 피곤해	매일 아침 피곤해	0
정말 힘드네	정말. 정말 쉽지가 않네. 이럴 땐 어떡해야 할까	1
  • labels 에 대한 설명을 데이터셋에 추가 필요
    • 0 : same meaning
    • 1: different meaning

Data split 기능 제공

train data 만 제공된 말뭉치의 경우 (random seed, ratio) 를 입력받아 subdata 를 만드는 기능 제공

SentencePair & LabeledSentencePair class

(question, answer), (sent1, sent2, label) 형식의 데이터에 모두 이용할 수 있는 General class 를 만든 뒤, KorpusData 를 상속하는 클래스에서 해당 클래스를 이용

[Corpus] Fix namuwikitext typo

안녕하세요
먼저, 이렇게 훌륭한 프로젝트를 시작해주신 것에 대해 감사의 말씀드립니다.

나무위키 데이터를 fetch 하던 중에 namuwiki 경로에서 데이터를 직접 불려오려고 했는데
not found 에러가 발생해서 보니 디렉토리명이 namiwiki 로 되어있었네요. link

의도하신 것인지 모르겠으나 혹시나 namuwiki를 잘못 작성하신가하여 올립니다.
에러와 관련된 이슈는 아니라 송구합니다.

다시 한번 감사드립니다.

NAMUWIKI_FETCH_INFORMATION = [
    {
        'url': 'https://github.com/lovit/namuwikitext/releases/download/v0.1/namuwikitext_20200302.v0.1.train.zip',
        'destination': 'namiwiki/namuwikitext_20200302.train.zip',
        'method': 'download & unzip'
    },
    {
        'url': 'https://github.com/lovit/namuwikitext/releases/download/v0.1/namuwikitext_20200302.v0.1.test.zip',
        'destination': 'namiwiki/namuwikitext_20200302.test.zip',
        'method': 'download & unzip'
    },
    {
        'url': 'https://github.com/lovit/namuwikitext/releases/download/v0.1/namuwikitext_20200302.v0.1.dev.zip',
        'destination': 'namiwiki/namuwikitext_20200302.dev.zip',
        'method': 'download & unzip'
    }
]
                    dirname = os.path.abspath(f'{root_dir}/namiwiki')
                    self.train = f'Namuwikitext corpus is downloaded. Open local directory {dirname}'
                    print('Continue to load `dev` and `test`')

Conventions

  • 며칠 간 작업을 함께 하면서 패키지 구조를 변경하는 일들이 발생했고, 그와 동시에 여러 개의 코퍼스에 대한 작업을 수행하다보니 conflict 가 날 가능성이 높아지고 있습니다.
  • 코드 관리 및 이후에 다른 분들과의 협업을 위해서도 간단한 convention 을 논의해 보면 좋을 것 같아요.
  • 아래에 comments 로 conventions 을 정하면 좋을 항목들을 열어두겠습니다. 수정을 통하여 내용을 보완해 보아요

commit conventions

  • 모든 commit 은 관련 이슈를 먼저 생성하고, 해당 이슈에 대한 설명은 issue/comments 에서 설명/논의합니다.
  • commit message 에 해당 이슈를 적어둡니다.
    Implement __len__ (#123)
    

branch conventions

  • master 는 배포/공개용으로만, dev 를 개발용으로 이용합니다.
    • 세부 개발은 dev 에서 브랜칭을 한 뒤에 dev < feature 로 PR 보내주세요.
    • 버전업데이트, 배포가 될 때 master < dev 로 머징합니다.
    • 그러므로 README 등의 문서 내 typo 수정 역시 dev 이하의 브랜치에서 수행합니다.
  • 한 브랜치 내에서는 그 브랜치에서 해결하려는 이슈에 관련된 파일만 수정합니다.
  • petitions#5 branch 에서는 KoreanPetitions 만 수정해야하며, NSMC 는 수정하지 않습니다.
  • NSMC 수정이 필요하다면 nsmc branch 에서 따로 작업합니다.
  • rebase 로 commit history 순서를 정렬합니다.

PR conventions

  • PR template 에 관련 이슈를 적는다. 두 개 이상의 이슈가 관련되어 있다면 모두 적는다.
    • 이슈가 없을 경우 생성하여 자세한 내용은 이슈에 기록한다.
    • typo 와 같이 이슈로 적을 필요가 없는 일에 대해서는 이슈를 적지 않아도 되며, 이때는 template 에 해당 내용을 간단히 기술한다.
  • PR 은 1명 이상 approved 가 되면 merge 한다.

Description convension

  • Korpus 에 입력되는 description 의 첫줄에는 author 를, 두번째 줄에는 repo 를, 세번째 줄에는 관련 reference 가 있다면 해당 reference 를 기술합니다. references 가 여러 개거나, 길이가 긴 경우에는 한 줄 띈 다음 - 기호로 구분하여 기록합니다. 코퍼스에 대한 설명은 한 줄 띈 다음에 자유롭게 기술합니다. 또한 description, license 는 4칸 들여쓰기 를 기준으로 작성합니다.
    (KorStS)
    Author : KakaoBrain
    Repository : https://github.com/kakaobrain/KorNLUDatasets
    References : 
        - Ham, J., Choe, Y. J., Park, K., Choi, I., & Soh, H. (2020). KorNLI and KorSTS: New Benchmark
           Datasets for Korean Natural Language Understanding. arXiv preprint arXiv:2004.03289.
           (https://arxiv.org/abs/2004.03289)

파일 별 다운로드

  • 여러 개의 파일로 구성된 코퍼스의 경우, 파일이 하나라도 없으면 전체를 다운로드 받습니다.
  • 파일별로 재 다운로드 받도록 fetch 기능을 수정하면 어떨까요?

KorNLI

(data snapshot)

sentence1	sentence2	gold_label
그리고 그가 말했다, "엄마, 저 왔어요."	그는 학교 버스가 그를 내려주자마자 엄마에게 전화를 걸었다.	neutral
그리고 그가 말했다, "엄마, 저 왔어요."	그는 한마디도 하지 않았다.	contradiction
그리고 그가 말했다, "엄마, 저 왔어요."	그는 엄마에게 집에 갔다고 말했다.	entailment
class LabeledSentencePairKorpusData(KorpusData):
    pairs : List[str]
    labels : List[Optional[str, int, float]]

    def __init__(self, texts, pairs, labels):
        if not (len(texts) == len(pairs) == len(labels)):
            raise ValueError('All length of `texts`, `pairs`, `labels` should be same')
        self.texts = texts
        self.pairs = pairs
        self.labels = labels

class KorNLIKorpusData(LabeledSentencePairKorpusData):
    def __init__(self, texts, pairs, labels):
        super().__init__(texts, pairs, labels)

KorSTS

  • #6 에서 언급된 데이터로, #10 와 같은 repository 에서 획득가능
  • 데이터가 (sent1, sent2, label) 외에 genre 정보가 추가로 존재
genre	filename	year	id	score	sentence1	sentence2
main-captions	MSRvid	2012test	0000	5.000	안전모를 가진 한 남자가 춤을 추고 있다.	안전모를 쓴 한 남자가 춤을 추고 있다.
main-captions	MSRvid	2012test	0002	4.750	어린아이가 말을 타고 있다.	아이가 말을 타고 있다.
main-captions	MSRvid	2012test	0003	5.000	한 남자가 뱀에게 쥐를 먹이고 있다.	남자가 뱀에게 쥐를 먹이고 있다.

#10 구현 뒤, genre attribute 추가하여 다음처럼 data class 만드는 것을 제안

class KorSTSKorpusData(LabeledSentencePairKorpusData):
    genres : List[str]

    def __init__(self, texts, pairs, labels, genres):
        super().__init__(texts, pairs, labels)
        if len(labels) != len(genres):
            raise ValueError('All length of `texts`, `pairs`, `labels`, `genres` should be same')
        self.genres = genres

네이버 x 창원대 NER

1	비토리오	PER_B
2	양일	DAT_B
3	만에	-
4	영사관	ORG_B
5	감호	CVL_B
6	용퇴,	-
7	항룡	-
8	압력설	-
9	의심만	-
10	가율	-

1	이	-
2	음경동맥의	-
3	직경이	-
4	8	NUM_B
5	19mm입니다	NUM_B
6	.	-

1	9세이브로	NUM_B
2	구완	-
3	30위인	NUM_B
4	LG	ORG_B

Release Korpora=0.1.0

0.1.0 에서 제공하기 위해 추가로 작업해야 하는 말뭉치 리스트

0.1.0 에서 제공하기 위해 추가로 작업해야 하는 이슈들

모두의 말뭉치

  • 신청 현황
    • 국립국어원의 원시말뭉치 사용 계약 때문에 데이터 다운로드 횟수 제한이 있음 (@ratsgo 님이 확인)
    • 데이터셋 다운로드용으로 신청한 내용은 위의 이유로 거절
    • login 후 파이썬 환경에서 다운로드 하는 것 역시 웹서버에서 기능 지원 불가하여 거절
  • local 에 데이터가 다운로드 되어있다고 가정한 뒤, class 를 이용하여 로딩하는 기능만 지원 가능
  • 이는 0.2.0 에서 지원하기로 결정 (@lovit , @ratsgo )

Show license and description when loading or fetching corpus

@ratsgo @hungry-wook

말뭉치를 공개해주신 분들의 노력을 알리는 것은 지속적으로 해야 하는 일이며, 말뭉치를 사용할 때 라이센스를 확인하는 작업은 정말로 중요하다고 생각합니다. 하여 fetch 혹은 Korpus class instance 를 만들 때 라이센스와 reference 가 포함된 description 을 print 하면 어떨까요?
그리고 이 기능은 0.1.0 부터 포함되어야 한다고 생각합니다.
자연어처리 커뮤니티 발전을 위해서 코퍼스 작업을 해주신 분들의 노력을 알려주는 것도 Korpora project 의 목표 중 하나라고 생각하며, 처음 릴리즈 할 때 이러한 의도가 패키지 내에서 보여졌으면 해서입니다.

valid test code

개요

마스터에 있는 테스트 코드들을 모두 정상 작동하도록 만들기

Description and license in `Korpus` and `KorpusData`

@ratsgo

  • 데이터 별 attributes 의 특징, reference 등의 내용을 기술하는 것이 필요해보입니다.
  • 또한 데이터 별로 라이센스가 다를 수 있기에 이 값도 명시하는 게 좋다고 생각합니다.
  • description, license 이라는 properties 를 만들고, 이 값을 class 에 적게 하는 것이 어떨까요?
class KorpusData:
    description : str  # description about each train / dev / test data including size ... 

    @property
    def description(self):
        return self.description

class Korpus:
    description : str  # description about all train / dev / test data including reference, size, composition of [train/dev/test] ...
    license : Union[str, None] = None

    @property
    def description(self):
        return self.description

    @property
    def license(self):
        return self.license

Korean Hate Speech Corpus

{'comments': '2,30대 골빈여자들은 이 기사에 다 모이는건가ㅋㅋㅋㅋ 이래서 여자는 투표권 주면 안된다. 엠넷사전투표나 하고 살아야지 계집들은',
 'contain_gender_bias': True,
 'bias': 'gender',
 'hate': 'hate',
 'news_title': '"“8년째 연애 중”…‘인생술집’ 블락비 유권♥전선혜, 4살차 연상연하 커플"'}
class KoreanHateSpeechKorpusData(KorpusData):
    gender_biases : List[bool]
    biases : List[str]
    hates : List[str]
    news_titles : List[str]

    def __init__(self, texts, news_titles, gender_biases, biases, hates):
        if not (len(texts) == len(news_titles) == len(gender_biases) == len(biases) == len(hates)):
            raise ValueError('All 5 arguments must be same length')
        self.texts = texts
        self.news_titles = news_titles
        self.gender_biases = gender_biases
        self.biases = biases
        self.hates = hates

데이터 다운로드 도중 취소한 케이스 대응

데이터 다운로드 도중에 취소한 경우,
해당 파일을 처음부터 새로 받는것이 아니라 그 다음 파일 다운로드로 넘어갑니다.
파일 용량 기준으로 기다운로드 여부를 체크하여야 할것 같습니다.

Readme typo

사용 예제에서 import하는 모듈명에 Korpus가 누락되었습니다.
KoreanHateSpeech -> KoreanHateSpeechKorpus
KoreanPetitions -> KoreanPetitionsKorpus
KorNLI -> KorNLIKorpus
KorSTS -> KorSTSKorpus
NSMC -> NSMCKorpus

샘플데이터 로딩 기능

용량이 큰 데이터의 일부만 샘플로 보고 싶은 경우 데이터의 개수를 제한하여 샘플만 로딩할 수 있는 기능을 제공하면 좋을듯 합니다.

데이터 관리 방법에 대한 질문

KoreanPetitions 데이터를 예시로 들어보면,

현재 코퍼스의 instance하나를 KoreanPetition, 데이터를 KoreanPetitionsData 클래스로 구현하고 있고 KoreanPetitionsData__getitem__에서 on-the-fly로 KoreanPetition dataclass를 만드는 식으로 관리되고 있는 것 같습니다.

KorpusData가 데이터를 List[KoreanPetition] (or List[CorpusSpecificSingleData]) 형태로 들고 있으면 굳이 코퍼스마다 *Data 클래스를 새로 정의해줄 필요가 없어 관리 차원에서 조금 더 유용할것 같은데요! 혹시 현재 구현처럼 관리되고 있는 특별한 이유가 있을까요?

Package license 작성

@ratsgo

정작 중요한 패키지의 라이센스를 명시하지 않았네요. 말뭉치들을 직접 재배포 하지 않고 원 위치를 공유하며 이를 다운로드 하는 경우에 말뭉치들의 라이센스를 그대로 따라야 하는지 확인이 필요합니다.
패키지 제작의 의도대로 가장 배타적이지 않은 라이센스를 정하도록해요.

Fetch only 기능 제공

  • 데이터를 손쉽게 로딩하는 기능 뿐 아니라, 데이터를 다운로드만 받는 기능도 제공해야 합니다.
  • 언어 모델을 학습하는 경우에는 용량이 큰 파일을 다운로드만 받은 후 파일 상태에서 학습에 이용하기도 합니다. 이를 위해서는 Korpora.load 기능 외에 아래와 같은 기능이 제공되어야 합니다.
Korpora.fetch('all')
Korpora.fetch('namuwikitext')

NSMC getitem 구현

(now)

nsmc = Korpora.load(nsmc)
nsmc[0]
~/git/Korpora/Korpora/korpora.py in __getitem__(self, index)
     12 
     13     def __getitem__(self, index):
---> 14         raise NotImplementedError('Implement __getitem__')
     15 
     16     def __iter__(self):

NotImplementedError: Implement __getitem__

NSMCExample 을 LabeledSentence 로 변경하기

(now)

@dataclass
class NSMCExample:
    text: str
    label: int

위 형식의 클래스는 sentence / document classification 에서 모두 이용될 수 있으므로 korpora.py 의 LabeledSentence 를 만든 뒤, 대체하는 것이 적절

utils.fetch 를 positional arguments 로 이용하는 함수들의 수정이 필요합니다.

최근에 fetch 함수에 method argument 가 arguments 중간에 새로 들어오면서 이전에 fetch 함수를 positional arguments 로 이용하던 함수들에서 문제가 발생했습니다.

(now) in korpora_nsmc.py

fetch(info['url'], local_path, 'nsmc', force_download)

위의 상황에서 fetch 함수에 들어가는 인자들을 확인하기 위하여 모든 인자를 풀어서 입력하던제

(desired)

fetch(info['url'], local_path, 'nsmc', info['method'], force_download)

혹은 keyword arguments 로 이용하는 것이 안전해 보입니다.

(desired)

fetch(
  url=info['url'],
  local_path=local_path,
  ..
)

namuwikitext

  • wikitext-2, wikitext-103 는 multiline texts 형식으로 위키피디아의 텍스트와 카테고리 이름을 정제한 데이터 (참고)
  • 나무위키에는 온라인에서 사용되는 문체가 포함된 다양한 종류의 문서들이 존재. 이를 wikitext 형식의 데이터로 가공하여 재배포

Korpus class 내에 데이터 다운로드 정보 두기

개요

  • 현재 데이터 다운로드 정보는 fetch.py의 DATA_LOCATIONS 변수에 담겨 있음
  • 이 정보를 Korpus 클래스를 상속받는 클래스에 두는 것으로 변경
  • 데이터마다 다운로드 정보는 유니크하기 때문에 Korpus 클래스에 두고 관리해도 큰 문제가 없음
  • 이렇게 했을 경우 데이터 추가 외부 PR시 Korpus 클래스를 상속받아 구현(이때 데이터 다운로드 위치, 전처리/cleansing 등만 정의)하면 된다는 장점이 있음

SentencePair, LabeledSentencePair 의 get_all_pairs, get_all_labels 기능 제공

  • LabeledSentencePair, (e.g. = KorNLI) 를 이용하는 모델의 학습은 ((sent1, sent2), label) 단위로 이뤄기 때문에 [(sent1, sent2), (sent1, sent2), ... ] 을 get_all_pairs 에서 [label, label, ...] 을 get_all_labels 에서 제공.
    • get_all_textslist of str 을 return 하는 것으로 오해할 수 있으므로 get_all_pairs 로 명명
  • 이와 비슷하게 SentencePair 도 get_all_pairs 기능을 제공
  • KorNLI 처럼 LabeledSentencePairKorpus 를 상속하는 클래스는 get_all_pairs, get_all_labels 를 제공

NSMCData format 통일

NSMCData class 는 KorpusData class 를 상속하지 않습니다. 이에 대한 협의 및 수정이 필요합니다.

NLI type custom dataclass 제공

KorNLI 외에 각자가 NLI type 으로 만드는 데이터가 있을 경우, 이를 로딩할 수 있도록 custom dataclass 를 제공합니다.

class CustomLabeledSentencePairKorpus(LabeledSentencePairKorpus):
    def __init__(self, files, ... ):
        # files 내 파일 이름 혹은 prefix 에 따라 LabeledSentencePairData class instance 생성

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.