Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
skyil7 committed Aug 22, 2019
0 parents commit eab53cb
Show file tree
Hide file tree
Showing 3 changed files with 318 additions and 0 deletions.
216 changes: 216 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@

# Created by https://www.gitignore.io/api/python,pycharm
# Edit at https://www.gitignore.io/?templates=python,pycharm

### PyCharm ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf

# Generated files
.idea/**/contentModel.xml

# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml

# Gradle
.idea/**/gradle.xml
.idea/**/libraries

# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr

# CMake
cmake-build-*/

# Mongo Explorer plugin
.idea/**/mongoSettings.xml

# File-based project format
*.iws

# IntelliJ
out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Cursive Clojure plugin
.idea/replstate.xml

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties

# Editor-based Rest Client
.idea/httpRequests

# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser

### PyCharm Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721

# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr

# Sonarlint plugin
.idea/sonarlint

### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

sample/
train/*
!train/TRAINED_MODEL_HERE.md

# End of https://www.gitignore.io/api/python,pycharm
99 changes: 99 additions & 0 deletions W2M.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import tensorflow as tf
import os

from magenta.protobuf import music_pb2
from magenta.music import sequences_lib, midi_io
from magenta.models.onsets_frames_transcription import configs, data, train_util, audio_label_data_utils, constants

# Trained Model Directory
MODEL_DIR = './train'

# Hyperparamter
config = configs.CONFIG_MAP['onsets_frames']
hparams = config.hparams
hparams.batch_size = 1
hparams.use_cudnn = False
hparams.audio_transform = False

example = tf.placeholder(tf.string, [None])

# Logging
tf.logging.info('model_dir=%s', MODEL_DIR)
tf.logging.info('checkpoint_path=%s', 'checkpoint')

# 배치 생성
dataset = data.provide_batch(examples=example, preprocess_examples=True,
params=hparams, is_training=False, shuffle_examples=False,
skip_n_initial_records=0)

# Estimator
estimator = train_util.create_estimator(config.model_fn, MODEL_DIR, hparams)

# 배치를 순환하는 이터레이터
iterator =dataset.make_initializable_iterator()
next_record = iterator.get_next()

sess = tf.Session()

#전역변수 및 로컬변수 초기화
sess.run([tf.initializers.global_variables(), tf.initializers.local_variables()])

#tensor로부터 사용하려는 데이터를 불러와 Dataset 인스턴스 생성
def input_fn(params):
del params
return tf.data.Dataset.from_tensors(sess.run(next_record))

def infer(filename):
# WAV 파일 Binary로 읽기
wav = open(filename,'rb')
wav_data = wav.read()
wav.close()

tf.logging.info('User .WAV FIle %s length %s bytes', filename, len(wav_data))

## 전처리
# 청크로 분할 후, Protocol Buffers 로 변환
to_process = []
examples = list(audio_label_data_utils.process_record(wav_data=wav_data, ns=music_pb2.NoteSequence(),
example_id=filename, min_length=0, max_length=-1, allow_empty_notesequence=True))

# 분할된 버퍼를 시리얼라이즈
to_process.append(examples[0].SerializeToString())

#############################################################

#시리얼라이즈한 버퍼를 iterator에 주입
sess.run(iterator.initializer, {example:to_process})

# Inference
predictions = list(estimator.predict(input_fn, yield_single_examples=False))
#가정 설정문으로 prediction size를 1로 보장
assert len(predictions) == 1

#예측 결과 불러오기
frame_predictions = predictions[0]['frame_predictions'][0]
onset_predictions = predictions[0]['onset_predictions'][0] # 치는 순간
velocity_values = predictions[0]['velocity_values'][0] #강약

#MIDI로 인코딩
sequence_prediction = sequences_lib.pianoroll_to_note_sequence(
frame_predictions,
frames_per_second=data.hparams_frames_per_second(hparams),
min_duration_ms=0,
min_midi_pitch=constants.MIN_MIDI_PITCH,
onset_predictions=onset_predictions,
velocity_values=velocity_values)

basename = os.path.split(os.path.splitext(filename)[0])[1] + '.mid'
output_filename = os.path.join('', basename)

midi_filename = (output_filename)
midi_io.sequence_proto_to_midi_file(sequence_prediction, midi_filename)

print('Program Ended, Your MIDI File is in', output_filename)

sess.close()

if __name__ == '__main__':
file = input('Input Your .WAV Filename:')
infer(file)
3 changes: 3 additions & 0 deletions train/TRAINED_MODEL_HERE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Download or Create Trained Model AND Place It Here

You can download Model from [Here](https://github.com/tensorflow/magenta/tree/master/magenta/models/onsets_frames_transcription).

0 comments on commit eab53cb

Please sign in to comment.