CmdMain.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. #include <QCoreApplication>
  2. #include <QDir>
  3. #include <QDirIterator>
  4. #include <QProcess>
  5. #include <QSettings>
  6. #include <QSharedMemory>
  7. #include <QStandardPaths>
  8. #include <QString>
  9. #include <QStringList>
  10. #include <QThread>
  11. #include <chrono>
  12. #include <filesystem>
  13. #include <iostream>
  14. #include <unordered_map>
  15. #include "DatabaseManager.hpp"
  16. #include "ImageHasher.hpp"
  17. #include <opencv2/core/utils/logger.hpp>
  18. void workerAdd(const QStringList &dirs);
  19. void cmdAdd(const QStringList &dirs);
  20. void cmdTh(int thValue);
  21. void cmdSearch(const QString &imageFile);
  22. void cmdStrict(bool strict);
  23. int main(int argc, char *argv[]) {
  24. // OpenCVの不要なINFOログ(並列バックエンド読み込み失敗など)を抑制する
  25. cv::utils::logging::setLogLevel(cv::utils::logging::LOG_LEVEL_ERROR);
  26. QCoreApplication::setOrganizationName("Yoneda");
  27. QCoreApplication::setApplicationName("DupFind");
  28. QCoreApplication app(argc, argv);
  29. QStringList args = app.arguments();
  30. if (args.size() < 2) {
  31. std::cerr << "Usage: DupFindCmd add <dir1> <dir2> ...\n"
  32. << " DupFindCmd th <N>\n"
  33. << " DupFindCmd search <image_file>\n"
  34. << " DupFindCmd strict [on|off]\n";
  35. return 1;
  36. }
  37. QString command = args[1];
  38. if (command == "--worker-add") {
  39. QStringList dirs = args.mid(2);
  40. workerAdd(dirs);
  41. return 0;
  42. } else if (command == "add") {
  43. if (args.size() < 3) {
  44. std::cerr << "Error: 'add' Requires at least one directory.\n";
  45. return 1;
  46. }
  47. cmdAdd(args.mid(2));
  48. return 0;
  49. } else if (command == "th") {
  50. if (args.size() != 3) {
  51. std::cerr << "Error: 'th' Requires exactly one integer.\n";
  52. return 1;
  53. }
  54. bool ok;
  55. int val = args[2].toInt(&ok);
  56. if (!ok || val < 0 || val > 32) {
  57. std::cerr << "Error: N must be an integer between 0 and 32.\n";
  58. return 1;
  59. }
  60. cmdTh(val);
  61. return 0;
  62. } else if (command == "search") {
  63. if (args.size() != 3) {
  64. std::cerr << "Error: 'search' Requires exactly one image file.\n";
  65. return 1;
  66. }
  67. cmdSearch(args[2]);
  68. return 0;
  69. } else if (command == "strict") {
  70. if (args.size() != 3) {
  71. std::cerr << "Error: 'strict' Requires exactly one argument.\n";
  72. return 1;
  73. }
  74. bool val = (args[2] == "on");
  75. cmdStrict(val);
  76. return 0;
  77. } else {
  78. std::cerr << "Unknown command: " << command.toStdString() << "\n";
  79. return 1;
  80. }
  81. }
  82. void cmdTh(int thValue) {
  83. QString confPath =
  84. QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
  85. if (!QDir().exists(confPath)) {
  86. QDir().mkpath(confPath);
  87. }
  88. QString iniPath = confPath + "/settings.ini";
  89. QSettings settings(iniPath, QSettings::IniFormat);
  90. settings.setValue("threshold", thValue);
  91. std::cout << "Successfully updated threshold to " << thValue << ".\n";
  92. }
  93. // GUI以外からディレクトリ追加を指示するコマンド
  94. // 設定ファイル(INI)を更新した上で、バックグラウンドのワーカプロセスをデタッチ起動する
  95. void cmdAdd(const QStringList &dirs) {
  96. QString confPath =
  97. QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
  98. if (!QDir().exists(confPath)) {
  99. QDir().mkpath(confPath);
  100. }
  101. QString iniPath = confPath + "/settings.ini";
  102. QSettings settings(iniPath, QSettings::IniFormat);
  103. QStringList existingDirs = settings.value("directories").toStringList();
  104. bool changed = false;
  105. for (const QString &dir : dirs) {
  106. if (!existingDirs.contains(
  107. dir, Qt::CaseInsensitive)) { // 念のためWindowsなど考慮
  108. existingDirs.append(dir);
  109. changed = true;
  110. }
  111. }
  112. if (changed) {
  113. settings.setValue("directories", existingDirs);
  114. }
  115. std::cout << "Started background scan.\n";
  116. // デタッチしてバックグラウンドプロセスを起動
  117. QString program = QCoreApplication::applicationFilePath();
  118. QStringList workerArgs;
  119. workerArgs << "--worker-add" << dirs;
  120. QProcess::startDetached(program, workerArgs);
  121. }
  122. // バックグラウンドで画像ファイルのハッシュ値(dHash,
  123. // pHash)を計算し、DBへ書き込む処理
  124. // GUI動作との競合を避ける配慮などが実装されている
  125. void workerAdd(const QStringList &dirs) {
  126. // バックグラウンド処理のためCPU優先度を下げる
  127. QThread::currentThread()->setPriority(QThread::IdlePriority);
  128. // GUIが起動しているか確認するための共有メモリ
  129. QSharedMemory sharedMem("DupFind_GUI_Instance");
  130. QString dataPath =
  131. QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation);
  132. if (!QDir().exists(dataPath)) {
  133. QDir().mkpath(dataPath);
  134. }
  135. QString dbPath = dataPath + "/dupfind_cache.db";
  136. DatabaseManager dbManager(dbPath.toStdString());
  137. if (!dbManager.open())
  138. return;
  139. auto cachedList = dbManager.getAllImages();
  140. std::unordered_map<std::string, ImageData> cache;
  141. for (const auto &img : cachedList) {
  142. cache[img.path] = img;
  143. }
  144. const QStringList filters = {"*.jpg", "*.png", "*.jpeg", "*.bmp",
  145. "*.webp", "*.tiff", "*.heic", "*.heif"};
  146. int count = 0;
  147. for (const QString &dirPath : dirs) {
  148. QDirIterator it(dirPath, filters, QDir::Files | QDir::NoSymLinks,
  149. QDirIterator::Subdirectories);
  150. while (it.hasNext()) {
  151. std::string stdPath = it.next().toStdString();
  152. // 少し粒度を荒くしてGUI起動チェック (10ファイルごと)
  153. if (count % 10 == 0) {
  154. if (sharedMem.attach()) {
  155. // GUIが共有メモリを確保している=起動中
  156. sharedMem.detach();
  157. return; // 即座に終了
  158. }
  159. }
  160. count++;
  161. try {
  162. std::error_code ec;
  163. auto currentSize = std::filesystem::file_size(stdPath, ec);
  164. auto currentMtime = std::chrono::duration_cast<std::chrono::seconds>(
  165. std::filesystem::last_write_time(stdPath, ec)
  166. .time_since_epoch())
  167. .count();
  168. auto cacheIt = cache.find(stdPath);
  169. if (cacheIt != cache.end()) {
  170. if (cacheIt->second.file_size == static_cast<int64_t>(currentSize) &&
  171. cacheIt->second.timestamp == static_cast<int64_t>(currentMtime)) {
  172. continue; // すでに最新ハッシュ計算済み
  173. }
  174. }
  175. cv::Mat img = ImageHasher::loadImage(stdPath);
  176. if (img.empty())
  177. continue;
  178. ImageData data;
  179. data.path = stdPath;
  180. data.dhash = ImageHasher::calculateDHash(img);
  181. data.phash = ImageHasher::calculatePHash(img);
  182. data.timestamp = currentMtime;
  183. data.file_size = currentSize;
  184. data.is_searched = false;
  185. dbManager.addImage(data);
  186. } catch (...) {
  187. // ファイルIOエラー等はスキップ
  188. }
  189. }
  190. }
  191. }
  192. // 指定された1つの画像ファイルと類似する「DB上の全ての画像」を検索してパスを出力するコマンド
  193. void cmdSearch(const QString &imageFile) {
  194. std::string stdPath = imageFile.toStdString();
  195. if (!std::filesystem::exists(stdPath)) {
  196. return;
  197. }
  198. cv::Mat img = ImageHasher::loadImage(stdPath);
  199. if (img.empty()) {
  200. return;
  201. }
  202. uint64_t dhash = ImageHasher::calculateDHash(img);
  203. uint64_t phash = ImageHasher::calculatePHash(img);
  204. QString confPath =
  205. QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
  206. if (!QDir().exists(confPath)) {
  207. QDir().mkpath(confPath);
  208. }
  209. QString iniPath = confPath + "/settings.ini";
  210. QSettings settings(iniPath, QSettings::IniFormat);
  211. int threshold = settings.value("threshold", 5).toInt();
  212. bool strict = settings.value("strict_mode", false).toBool();
  213. QString dataPath =
  214. QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation);
  215. if (!QDir().exists(dataPath)) {
  216. QDir().mkpath(dataPath);
  217. }
  218. QString dbPath = dataPath + "/dupfind_cache.db";
  219. DatabaseManager dbManager(dbPath.toStdString());
  220. if (!dbManager.open())
  221. return;
  222. auto allImages = dbManager.getAllImages();
  223. for (const auto &imgData : allImages) {
  224. int distD = ImageHasher::hammingDistance(dhash, imgData.dhash);
  225. int distP = ImageHasher::hammingDistance(phash, imgData.phash);
  226. bool similar = strict ? (distD <= threshold && distP <= threshold)
  227. : (distD <= threshold || distP <= threshold);
  228. if (similar) {
  229. std::cout << imgData.path << "\n";
  230. }
  231. }
  232. }
  233. void cmdStrict(bool strict) {
  234. QString confPath =
  235. QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
  236. if (!QDir().exists(confPath)) {
  237. QDir().mkpath(confPath);
  238. }
  239. QString iniPath = confPath + "/settings.ini";
  240. QSettings settings(iniPath, QSettings::IniFormat);
  241. settings.setValue("strict_mode", strict);
  242. std::cout << "Successfully updated strict mode to " << (strict ? "on" : "off")
  243. << ".\n";
  244. }