CmdMain.cpp 11 KB

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