about summary refs log tree commit diff stats
path: root/generator/generator.cpp
blob: 4244fd271bc90d2c3610b1f0ab59b6d789b3af7e (plain) (blame)
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
#include "generator.h"
#include <stdexcept>
#include <iostream>
#include <fstream>
#include <dirent.h>
#include <json.hpp>
#include <hkutil/progress.h>
#include <hkutil/string.h>

namespace cadence {
  namespace generator {

    generator::generator(
      std::string inputpath,
      std::string outputpath) :
        inputpath_(inputpath),
        db_(outputpath, hatkirby::dbmode::create)
    {
      // Add directory separator to input path
      if ((inputpath_.back() != '/') && (inputpath_.back() != '\\'))
      {
        inputpath_ += '/';
      }

      inputpath_ += "highlevel/";
    }

    void generator::run()
    {
      // Creates the datafile.
      writeSchema();

      // Scans the AcousticBrainz data dump and generates a list of all of the
      // files in the dump.
      scanDirectories();

      // Parses each data file and enters it into the database.
      parseData();
    }

    void generator::writeSchema()
    {
      std::ifstream file("schema.sql");
      if (!file)
      {
        throw std::invalid_argument("Could not find database schema");
      }

      std::ostringstream schemaBuilder;
      std::string line;
      while (std::getline(file, line))
      {
        if (line.back() == '\r')
        {
          line.pop_back();
        }

        schemaBuilder << line;
      }

      std::string schema = schemaBuilder.str();
      auto queries = hatkirby::split<std::list<std::string>>(schema, ";");
      hatkirby::progress ppgs("Writing database schema...", queries.size());
      for (std::string query : queries)
      {
        if (!queries.empty())
        {
          db_.execute(query);
        }

        ppgs.update();
      }
    }

    void generator::scanDirectories()
    {
      std::cout << "Scanning AcousticBrainz dump..." << std::endl;

      DIR* topdir;
      if ((topdir = opendir(inputpath_.c_str())) == nullptr)
      {
        throw std::invalid_argument("Invalid AcousticBrainz data directory");
      }

      struct dirent* topent;
      while ((topent = readdir(topdir)) != nullptr)
      {
        if (topent->d_name[0] != '.')
        {
          std::string directory = inputpath_ + topent->d_name + "/";

          DIR* subdir;
          if ((subdir = opendir(directory.c_str())) == nullptr)
          {
            throw std::invalid_argument(
              "Invalid AcousticBrainz data directory");
          }

          struct dirent* subent;
          while ((subent = readdir(subdir)) != nullptr)
          {
            if (subent->d_name[0] != '.')
            {
              std::string subdirectory = directory + subent->d_name + "/";

              DIR* subsubdir;
              if ((subsubdir = opendir(subdirectory.c_str())) == nullptr)
              {
                throw std::invalid_argument(
                  "Invalid AcousticBrainz data directory");
              }

              struct dirent* subsubent;
              while ((subsubent = readdir(subsubdir)) != nullptr)
              {
                if (subsubent->d_name[0] != '.')
                {
                  std::string datafile = subdirectory + subsubent->d_name;

                  datafiles_.push_back(datafile);
                }
              }

              closedir(subsubdir);
            }
          }

          closedir(subdir);
        }
      }

      closedir(topdir);
    }

    void generator::parseData()
    {
      hatkirby::progress ppgs(
        "Parsing AcousticBrainz data files...",
        datafiles_.size());

      for (std::string datafile : datafiles_)
      {
        ppgs.update();

        nlohmann::json jsonData;
        {
          std::ifstream dataStream(datafile);
          dataStream >> jsonData;
        }

        try
        {
          auto& hl = jsonData["highlevel"];

          double danceable = hl["danceability"]["all"]["danceable"];
          double acoustic = hl["mood_acoustic"]["all"]["acoustic"];
          double aggressive = hl["mood_aggressive"]["all"]["aggressive"];
          double electronic = hl["mood_electronic"]["all"]["electronic"];
          double happy = hl["mood_happy"]["all"]["happy"];
          double party = hl["mood_party"]["all"]["party"];
          double relaxed = hl["mood_relaxed"]["all"]["relaxed"];
          double sad = hl["mood_sad"]["all"]["sad"];
          double instrumental = hl["voice_instrumental"]["all"]["instrumental"];

          std::string title = jsonData["metadata"]["tags"]["title"][0];
          std::string artist = jsonData["metadata"]["tags"]["artist"][0];

          uint64_t songId = db_.insertIntoTable(
            "songs",
            {
              { "title", title },
              { "artist", artist }
            });

          std::list<std::string> moods;

          // ~38%
          if ((party > 0.5) || (danceable > 0.75))
          {
            moods.push_back("party");
          }

          // ~38%
          if ((relaxed > 0.81) || (acoustic > 0.5))
          {
            moods.push_back("chill");
          }

          // ~42%
          if ((aggressive > 0.5) || (electronic > 0.95))
          {
            moods.push_back("crazy");
          }

          // ~30%
          if (happy > 0.5)
          {
            moods.push_back("happy");
          }

          // ~30%
          if (sad > 0.5)
          {
            moods.push_back("sad");
          }

          // ~38%
          if (instrumental > 0.9)
          {
            moods.push_back("instrumental");
          }

          // ~34%
          if (instrumental < 0.2)
          {
            moods.push_back("vocal");
          }

          // ~1%
          if (moods.empty())
          {
            moods.push_back("unknown");
          }

          for (const std::string& mood : moods)
          {
            db_.insertIntoTable(
              "moods",
              {
                { "song_id", static_cast<int>(songId) },
                { "mood", mood }
              });
          }
        } catch (const std::domain_error& ex)
        {
          // Weird data. Ignore silently.
        }
      }
    }

  };
};