turn into c++ : import sys, os import numpy as np from PyQt5.QtWidgets import…
- User
turn into c++ : import sys, os import numpy as np from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import Qt, QUrl, QTimer from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineSettings from PIL import Image import urllib.parse
def getRandomFEN(): fen_chars = list('1KQRBNPkqrbnp') pieces = np.random.choice(fen_chars, 64) fen = '/'.join([''.join(pieces[i*8:(i+1)*8]) for i in range(8)]) return fen
class Screenshot(QWebEngineView):
def __init__(self): super().__init__() self.current_index = 0 self.total_screenshots = 0 self.output_filenames = [] self.theme_index = 0 self.piece_index = 0 self.background_index = 0 self.themes = [] self.pieceSets = [] self.backgrounds = [] self.out_folder = '' def capture(self, url, output_file, total_screenshots, output_filenames, themes, pieceSets, backgrounds, out_folder): self.output_file = output_file self.total_screenshots = total_screenshots self.output_filenames = output_filenames self.themes = themes self.pieceSets = pieceSets self.backgrounds = backgrounds self.out_folder = out_folder self.load(QUrl(url)) self.loadFinished.connect(self.on_loaded) self.setAttribute(Qt.WA_DontShowOnScreen) self.page().settings().setAttribute(QWebEngineSettings.ShowScrollBars, False) self.show() def on_loaded(self): self.resize(1920, 1080) QTimer.singleShot(2000, self.take_screenshot) def take_screenshot(self): self.grab().save(self.output_file, b'PNG') QTimer.singleShot(1000, self.process_next) def process_next(self): if os.path.exists(self.output_file): im = Image.open(self.output_file).crop([488, 167, 1118, 797]) im.save(self.output_file) self.current_index += 1 # Update indices for theme, piece set, and background before generating the next screenshot if self.current_index >= self.total_screenshots: self.current_index = 0 self.theme_index += 1 # Increment the theme first # After all themes are used, move to the next piece set if self.theme_index >= len(self.themes): self.theme_index = 0 # Reset the theme index self.piece_index += 1 # Increment the piece set # After all piece sets are used, move to the next background if self.piece_index >= len(self.pieceSets): self.piece_index = 0 # Reset the piece set index self.background_index += 1 # Increment the background # If all backgrounds have been used, stop the app if self.background_index >= len(self.backgrounds): self.app.quit() # Quit the app when all combinations are done return print(f"Theme: {self.themes[self.theme_index]}, Piece: {self.pieceSets[self.piece_index]}, Background: {self.backgrounds[self.background_index]}") fen = getRandomFEN().replace('/', '-') next_output_file = f"{self.out_folder}/{fen}.png" theme = self.themes[self.theme_index] piece = self.pieceSets[self.piece_index] background = self.backgrounds[self.background_index] # URL Encoding for theme encoded_theme = urllib.parse.quote(theme) url = f"http://en.lichess.org/editor/{fen.replace('-', '/')}?theme={encoded_theme}&pieceSet={piece}&bg={background}" print(theme,piece) print(f"#{self.current_index} : {fen}") print(f"\tSaved screenshot to '{next_output_file}'") self.capture(url, next_output_file, self.total_screenshots, self.output_filenames, self.themes, self.pieceSets, self.backgrounds, self.out_folder) print("\t...Success") else: print(f"File not found: {self.output_file}") QTimer.singleShot(2000, self.process_next)app = QApplication(sys.argv) s = Screenshot() s.app = app
themes = ["brown","wood","wood2","wood3","wood4","maple","maple2","horsey","leather","blue","blue2","blue3","canvas","blue-marble","ic","green","marble","green-plastic","olive","grey","metal","newspaper","purple","purple-diag","pink"] pieceSets = ["cburnett","merida","alpha","pirouetti","chessnut","chess7","reillycraig","companion","riohacha","kosal","leipzig","fantasy","spatial","celtic","california","caliente","pixel","maestro","fresca","cardinal","gioco","tatiana","staunty","cooke","monarchy","governor","dubrovny","icpieces","mpchess","kiwen-suwi","letter","shapes"] backgrounds = ["light"]
Number of random screenshots to generate per combination
N = 3
out_folder = 'train_images' if not os.path.exists(out_folder): os.makedirs(out_folder, exist_ok=True)
fen = getRandomFEN().replace('/', '-') s.output_filenames = [f"{out_folder}/{fen}.png" for i in range(N)] print(f"#0 : {fen}") print(f"\tSaved screenshot to '{s.output_filenames[0]}'")
URL Encoding for theme
encoded_theme = urllib.parse.quote(themes[0]) url = f"http://en.lichess.org/editor/{fen.replace('-', '/')}?theme={encoded_theme}&piece={pieceSets[0]}&bg={backgrounds[0]}" s.capture(url, s.output_filenames[0], N, s.output_filenames, themes, pieceSets, backgrounds, out_folder) print("\t...Success")
sys.exit(app.exec_())
- Assistant
Certainly! Below is a C++ version of your Python script using Qt. This code performs the same tasks:
- Generates random FEN strings
- Constructs URLs to display the chess positions with different themes and piece sets on Lichess
- Captures screenshots of the chess board from the web page
- Crops and saves the images
- Iterates through all combinations of themes, piece sets, and backgrounds
Please ensure you have the Qt framework installed with the necessary modules (
QtWidgets,QtWebEngineWidgets, andQtGui).// main.cpp #include <QApplication> #include <QWebEngineView> #include <QWebEngineSettings> #include <QWebEnginePage> #include <QTimer> #include <QImage> #include <QString> #include <QUrl> #include <QFile> #include <QDir> #include <QPainter> #include <QRandomGenerator> #include <QDebug> #include <QObject> #include <QScreen> #include <QPixmap> #include <QWebEngineProfile> QString getRandomFEN() { QString fenChars = "1KQRBNPkqrbnp"; QString pieces; for (int i = 0; i < 64; ++i) { int index = QRandomGenerator::global()->bounded(fenChars.length()); pieces.append(fenChars.at(index)); } QStringList rows; for (int i = 0; i < 8; ++i) { rows.append(pieces.mid(i*8, 8)); } return rows.join('/'); } class Screenshot : public QWebEngineView { Q_OBJECT public: explicit Screenshot(QApplication *app, QWidget *parent = nullptr); void capture(const QUrl &url, const QString &outputFile); void setParameters(int totalScreenshots, const QStringList &themes, const QStringList &pieceSets, const QStringList &backgrounds, const QString &outFolder); private slots: void onLoaded(bool ok); void takeScreenshot(); void processNext(); private: QApplication *app; int currentIndex = 0; int totalScreenshots = 0; int themeIndex = 0; int pieceIndex = 0; int backgroundIndex = 0; QStringList themes; QStringList pieceSets; QStringList backgrounds; QString outFolder; QString outputFile; }; Screenshot::Screenshot(QApplication *app, QWidget *parent) : QWebEngineView(parent), app(app) { connect(this, &QWebEngineView::loadFinished, this, &Screenshot::onLoaded); this->setAttribute(Qt::WA_DontShowOnScreen); this->page()->settings()->setAttribute(QWebEngineSettings::ShowScrollBars, false); } void Screenshot::setParameters(int totalScreenshots, const QStringList &themes, const QStringList &pieceSets, const QStringList &backgrounds, const QString &outFolder) { this->totalScreenshots = totalScreenshots; this->themes = themes; this->pieceSets = pieceSets; this->backgrounds = backgrounds; this->outFolder = outFolder; } void Screenshot::capture(const QUrl &url, const QString &outputFile) { this->outputFile = outputFile; this->load(url); this->show(); } void Screenshot::onLoaded(bool ok) { if (!ok) { qDebug() << "Failed to load the page."; return; } this->resize(1920, 1080); QTimer::singleShot(2000, this, &Screenshot::takeScreenshot); } void Screenshot::takeScreenshot() { this->page()->grab().then([=](const QImage &image) { image.save(this->outputFile, "PNG"); QTimer::singleShot(1000, this, &Screenshot::processNext); }); } void Screenshot::processNext() { QFile file(this->outputFile); if (file.exists()) { QImage image(this->outputFile); QRect rect(488, 167, 630, 630); QImage croppedImage = image.copy(rect); croppedImage.save(this->outputFile); currentIndex += 1; // Update indices for theme, piece set, and background before generating the next screenshot if (currentIndex >= totalScreenshots) { currentIndex = 0; themeIndex += 1; // Increment the theme first // After all themes are used, move to the next piece set if (themeIndex >= themes.length()) { themeIndex = 0; // Reset the theme index pieceIndex += 1; // Increment the piece set // After all piece sets are used, move to the next background if (pieceIndex >= pieceSets.length()) { pieceIndex = 0; // Reset the piece set index backgroundIndex += 1; // Increment the background // If all backgrounds have been used, stop the app if (backgroundIndex >= backgrounds.length()) { app->quit(); // Quit the app when all combinations are done return; } } } } qDebug() << "Theme:" << themes.at(themeIndex) << ", Piece:" << pieceSets.at(pieceIndex) << ", Background:" << backgrounds.at(backgroundIndex); QString fen = getRandomFEN().replace("/", "-"); QString nextOutputFile = QString("%1/%2.png").arg(outFolder, fen); QString theme = themes.at(themeIndex); QString piece = pieceSets.at(pieceIndex); QString background = backgrounds.at(backgroundIndex); QString encodedTheme = QUrl::toPercentEncoding(theme); QString urlString = QString("https://lichess.org/editor/%1?theme=%2&piece=%3&bg=%4") .arg(fen.replace("-", "/"), encodedTheme, piece, background); QUrl url(urlString); qDebug() << QString("#%1 : %2").arg(currentIndex).arg(fen); qDebug() << QString("\tSaved screenshot to '%1'").arg(nextOutputFile); capture(url, nextOutputFile); qDebug() << "\t...Success"; } else { qDebug() << "File not found:" << outputFile; QTimer::singleShot(2000, this, &Screenshot::processNext); } } int main(int argc, char *argv[]) { QApplication app(argc, argv); Screenshot s(&app); QStringList themes = {"brown","wood","wood2","wood3","wood4","maple","maple2","horsey","leather","blue","blue2","blue3","canvas","blue-marble","ic","green","marble","green-plastic","olive","grey","metal","newspaper","purple","purple-diag","pink"}; QStringList pieceSets = {"cburnett","merida","alpha","pirouetti","chessnut","chess7","reillycraig","companion","riohacha","kosal","leipzig","fantasy","spatial","celtic","california","caliente","pixel","maestro","fresca","cardinal","gioco","tatiana","staunty","cooke","monarchy","governor","dubrovny","icpieces","mpchess","kiwen-suwi","letter","shapes"}; QStringList backgrounds = {"light"}; // Number of random screenshots to generate per combination int N = 3; QString outFolder = "train_images"; QDir dir; if (!dir.exists(outFolder)) { dir.mkpath(outFolder); } QString fen = getRandomFEN().replace("/", "-"); QString outputFile = QString("%1/%2.png").arg(outFolder, fen); s.setParameters(N, themes, pieceSets, backgrounds, outFolder); QString encodedTheme = QUrl::toPercentEncoding(themes.first()); QString urlString = QString("https://lichess.org/editor/%1?theme=%2&piece=%3&bg=%4") .arg(fen.replace("-", "/"), encodedTheme, pieceSets.first(), backgrounds.first()); QUrl url(urlString); qDebug() << QString("#0 : %1").arg(fen); qDebug() << QString("\tSaved screenshot to '%1'").arg(outputFile); s.capture(url, outputFile); qDebug() << "\t...Success"; return app.exec(); } #include "main.moc"Explanation and Notes:
-
Qt Classes Used:
QApplication: Manages the GUI application's control flow and main settings.QWebEngineView: A widget that can render web content.QWebEngineSettings: Provides access to the settings of the web engine.QTimer: Provides repetitive and single-shot timers.QImage: Image handling class.QUrl: Handling and manipulating URLs.QDir: Provides access to directory structures and their contents.QRandomGenerator: For generating random numbers.QDebug: For logging debug messages.
-
Random FEN Generation:
- The
getRandomFENfunction generates a random FEN string similar to your Python code. It chooses random characters from'1KQRBNPkqrbnp'to represent empty squares and pieces.
- The
-
Screenshot Class:
- Inherits from
QWebEngineViewto use the web rendering capabilities. - Contains slots and methods to handle loading the web page, capturing the screenshot, processing it, and moving to the next combination.
- Inherits from
-
Image Cropping:
- After taking the screenshot, the image is cropped using
QImage::copyto match the crop parameters from your Python code.
- After taking the screenshot, the image is cropped using
-
URL Construction:
- Uses
QUrl::toPercentEncodingto encode the theme parameter in the URL. - Constructs the URL similar to your Python code, pointing to Lichess's board editor with the specified parameters.
- Uses
-
Iteration Logic:
- The
processNextfunction updates the indices for themes, piece sets, and backgrounds, ensuring all combinations are processed. - The application quits when all combinations have been processed.
- The
-
Main Function:
- Initializes the application and the
Screenshotobject. - Sets the parameters (themes, piece sets, backgrounds, and output folder).
- Starts the process by capturing the first screenshot.
- Initializes the application and the
-
Compiling the Code:
- Save the code in a file named
main.cpp. - Use
qmakeandmaketo compile the application. - Ensure you include
QT += widgets webenginewidgetsin your.profile.
Example
.profile:QT += widgets webenginewidgets SOURCES += main.cpp - Save the code in a file named
-
Note on Asynchronous Calls:
- The
QWebEnginePage::grabfunction returns aQWebEngineCallback, so we use thethenmethod to handle the image once it's ready.
- The
-
Including "main.moc":
- At the end of your
main.cpp, include#include "main.moc"to ensure that Qt's Meta-Object Compiler processes the slots and signals.
- At the end of your
Important Considerations:
- Since Lichess might have updated their URL scheme or may have protections against automated scraping, ensure you have permission to scrape their site, or consider using a local HTML page or an API if available.
- Always handle exceptions and errors, especially network-related ones.
- Ensure the Qt version you are using supports the
QtWebEnginemodule. If not, you might need to install it separately or adjust your code to useQWebView(fromQtWebKit), though it's deprecated in recent Qt versions.
Running the Application:
When you run the application, it will open web pages in the background (not displayed due to
Qt::WA_DontShowOnScreen), take screenshots, crop them, and save them to the specifiedtrain_imagesfolder. It will iterate through all combinations of themes, piece sets, and backgrounds, generatingNrandom positions for each combination.
Feel free to ask if you have any questions or need further assistance with the code!