diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b1dff0d --- /dev/null +++ b/.gitignore @@ -0,0 +1,45 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Kotlin ### +.kotlin + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..574bf71 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,56 @@ +import org.jetbrains.compose.desktop.application.dsl.TargetFormat + +plugins { + kotlin("jvm") version "2.0.0" + kotlin("plugin.serialization") version "2.0.0" + + kotlin("plugin.compose") version "2.0.0" // ✅ Add this line + id("org.jetbrains.compose") version "1.6.11" +} + +group = "kr.lunatic.bum" +version = "1.0-SNAPSHOT" + +kotlin { + jvmToolchain(21) // ✅ Ensure this line is present and set to 21 +} + +repositories { + mavenCentral() + google() + maven("https://maven.datlag.dev/snapshots") +} + +dependencies { + // Jetpack Compose for Desktop UI + implementation(compose.desktop.currentOs) + + // Ktor for HTTP Client (LLM API 호출용) + val ktorVersion = "2.3.12" + implementation("io.ktor:ktor-client-cio:$ktorVersion") + implementation("io.ktor:ktor-client-content-negotiation:$ktorVersion") + implementation("io.ktor:ktor-serialization-kotlinx-json:$ktorVersion") + + // Jsoup for HTML Parsing + implementation("org.jsoup:jsoup:1.16.1") + + // Kotlinx Serialization for JSON + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.1") + + // Selenium for Headless Browser Automation + implementation("org.seleniumhq.selenium:selenium-java:4.22.0") + + implementation("org.slf4j:slf4j-simple:1.7.36") + +} + +compose.desktop { + application { + mainClass = "MainKt" + nativeDistributions { + targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb) + packageName = "AutoBlogApp" + packageVersion = "1.0.0" + } + } +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..7fc6f1f --- /dev/null +++ b/gradle.properties @@ -0,0 +1 @@ +kotlin.code.style=official diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..ac1b06f --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..6fa3f32 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,4 @@ +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0" +} +rootProject.name = "getter" \ No newline at end of file diff --git a/src/main/kotlin/Main.kt b/src/main/kotlin/Main.kt new file mode 100644 index 0000000..f97345e --- /dev/null +++ b/src/main/kotlin/Main.kt @@ -0,0 +1,475 @@ +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Window +import androidx.compose.ui.window.application +import io.ktor.client.* +import io.ktor.client.call.* +import io.ktor.client.engine.cio.* +import io.ktor.client.plugins.contentnegotiation.* +import io.ktor.client.request.* +import io.ktor.client.statement.* +import io.ktor.http.* +import io.ktor.serialization.kotlinx.json.* +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json +import org.jsoup.Jsoup +import org.openqa.selenium.By +import org.openqa.selenium.chrome.ChromeDriver +import org.openqa.selenium.chrome.ChromeOptions +import java.io.File +import java.text.SimpleDateFormat +import java.util.* +import kotlin.io.path.Path +import kotlin.io.path.readText + +// --- 데이터 클래스 정의 --- + +@Serializable data class AnythingLLMChatRequest(val message: String) +@Serializable data class AnythingLLMChatResponse(val textResponse: String) +data class SearchResult(val title: String, val url: String) + +// --- 전역 변수 및 헬퍼 --- + +private val httpClient = HttpClient(CIO) { + install(ContentNegotiation) { + json(Json { isLenient = true; ignoreUnknownKeys = true }) + } +} + +fun logMessage(logs: MutableList, message: String) { + val timestamp = SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(Date()) + logs.add(0, "$timestamp: $message") +} + +// --- 핵심 기능 함수들 --- + +suspend fun fetchGoogleTrends(logs: MutableList, isBrowserVisible: Boolean): List { + logMessage(logs, "Google Trends 페이지 스크랩 시작...") + val trendsUrl = "https://trends.google.co.kr/trends/trendingsearches/daily?geo=KR" + val options = ChromeOptions().apply { + if (!isBrowserVisible) { + addArguments("--headless=new") + } + addArguments("--disable-gpu") + } + val driver = ChromeDriver(options) + val keywords = mutableListOf() + return try { + driver.get(trendsUrl) + Thread.sleep(2000) + val elements = driver.findElements(By.xpath("//tr[count(td)=7]/td[2]")) + for (element in elements) { + val keywordText = element.text + if (keywordText.isNotBlank()) { + keywords.add(keywordText) + } + } + logMessage(logs, "✅ Google Trends 키워드 ${keywords.size}개 스크랩 완료.") + keywords + } catch (e: Exception) { + logMessage(logs, "❌ Google Trends 스크랩 오류: ${e.message}") + e.printStackTrace() + emptyList() + } finally { + driver.quit() + } +} + +suspend fun searchOnGoogle(keyword: String, logs: MutableList, isBrowserVisible: Boolean): List { + logMessage(logs, "'$keyword' 키워드로 Google 검색 시작...") + val options = ChromeOptions().apply { + if (!isBrowserVisible) { + addArguments("--headless=new") + } + addArguments("--disable-gpu") + } + val driver = ChromeDriver(options) + val results = mutableListOf() + try { + driver.get("https://www.google.com/search?q=$keyword") + Thread.sleep(2000) + val resultElements = driver.findElements(By.cssSelector("div[data-rpos]")) + for (element in resultElements.take(10)) { + try { + val titleElement = element.findElement(By.cssSelector("h3")) + val linkElement = element.findElement(By.cssSelector("a")) + val title = titleElement.text + val url = linkElement.getAttribute("href") + if (title.isNotBlank() && url.isNotBlank()) { + results.add(SearchResult(title, url)) + } + } catch (e: Exception) { + // 개별 검색 결과 파싱 오류는 무시 + } + } + logMessage(logs, "✅ '$keyword' 검색 결과 ${results.size}개 수집 완료.") + } catch (e: Exception) { + logMessage(logs, "❌ Google 검색 중 오류: ${e.message}") + e.printStackTrace() + } finally { + driver.quit() + } + return results +} + +suspend fun scrapeArticleByUrl(url: String, logs: MutableList, isBrowserVisible: Boolean): String { + logMessage(logs, "URL 스크랩 시작: $url") + val options = ChromeOptions().apply { + if (!isBrowserVisible) { + addArguments("--headless=new") + } + addArguments("--disable-gpu") + } + val driver = ChromeDriver(options) + return try { + driver.get(url) + Thread.sleep(2000) + val finalHtml = driver.pageSource + val doc = Jsoup.parse(finalHtml) + val articleContent = doc.select("article, .article-body, #article_body, .news-article-body-view").text() + if (articleContent.isBlank()) { + logMessage(logs, "⚠️ 기사 본문을 찾을 수 없습니다.") + "기사 본문을 찾을 수 없습니다." + } else { + logMessage(logs, "✅ URL 스크랩 완료. (총 ${articleContent.length}자)") + articleContent + } + } catch (e: Exception) { + logMessage(logs, "❌ URL 스크랩 중 오류: ${e.message}") + e.printStackTrace() + "페이지 스크랩 중 오류 발생: ${e.message}" + } finally { + driver.quit() + } +} + +suspend fun generateBlogPostWithLocalLLM(fileNames: List, userDirection: String, logs: MutableList): String { + logMessage(logs, "LLM 블로그 글 생성 요청 (${fileNames.size}개 파일 기반)...") + val apiKey = System.getenv("ANYTHINGLLM_API_KEY") ?: "YOUR_API_KEY_HERE" + val fileNamesString = fileNames.joinToString(", ") + + val finalPrompt = """ + 내 지식 베이스에 있는 다음 문서들을 종합적으로 참고해서 아래 '요청사항'에 맞춰 SEO에 최적화된 블로그 글을 작성해줘. 제목도 2~3개 추천해줘. + + --- 참고 문서 --- + $fileNamesString + + --- 요청사항 --- + $userDirection + """.trimIndent() + + val requestBody = AnythingLLMChatRequest(message = finalPrompt) + return try { + val response: AnythingLLMChatResponse = httpClient.post("http://localhost:3001/api/v1/workspace/my/chat") { + header("Authorization", "Bearer $apiKey") + contentType(ContentType.Application.Json) + setBody(requestBody) + }.body() + logMessage(logs, "✅ LLM 블로그 글 생성 완료.") + response.textResponse + } catch (e: Exception) { + logMessage(logs, "❌ LLM 호출 중 오류: ${e.message}") + e.printStackTrace() + "블로그 글 생성 실패: ${e.message}" + } +} + +fun saveContentToFile(keyword: String, content: String, logs: MutableList) { + try { + val directory = File("/Users/jibumhan/autoblog_content") + if (!directory.exists()) directory.mkdirs() + val sanitizedKeyword = keyword.replace(Regex("[^A-Za-z0-9ㄱ-ㅎㅏ-ㅣ가-힣]"), "") + val fileName = "${sanitizedKeyword}_${System.currentTimeMillis()}.txt" + val file = File(directory, fileName) + file.writeText(content) + logMessage(logs, "✅ '${file.path}'에 스크랩 내용 저장 완료.") + } catch (e: Exception) { + logMessage(logs, "❌ 파일 저장 중 오류: ${e.message}") + e.printStackTrace() + } +} + +fun loadScrapedFiles(logs: MutableList): List { + logMessage(logs, "스크랩된 파일 목록 로딩...") + return try { + val directory = File("scraped_articles") + if (!directory.exists() || !directory.isDirectory) { + logMessage(logs, "⚠️ 'scraped_articles' 폴더를 찾을 수 없습니다.") + return emptyList() + } + val files = directory.listFiles { _, name -> name.endsWith(".txt") } + ?.sortedByDescending { it.lastModified() } + ?: emptyList() + logMessage(logs, "✅ 파일 ${files.size}개 로딩 완료.") + files + } catch (e: Exception) { + logMessage(logs, "❌ 파일 로딩 중 오류: ${e.message}") + emptyList() + } +} + + +// --- UI 컴포넌트 --- + +@Composable +fun App() { + var tabIndex by remember { mutableStateOf(0) } + val tabs = listOf("워크플로우", "통신 로그", "블로그 결과") + val coroutineScope = rememberCoroutineScope() + + // --- 상태 관리 --- + var keywords by remember { mutableStateOf>(emptyList()) } + var searchResults by remember { mutableStateOf>(emptyList()) } + var blogPostResult by remember { mutableStateOf("LLM으로부터 생성된 블로그 글이 여기에 표시됩니다.") } + val logMessages = remember { mutableStateListOf() } + var isLoading by remember { mutableStateOf(false) } + var selectedKeyword by remember { mutableStateOf("") } + var userPrompt by remember { mutableStateOf("친근하고 유용한 정보 전달 스타일로 작성해줘.") } + var isBrowserVisible by remember { mutableStateOf(true) } // 브라우저 가시성 상태 + + // 파일 관리 상태 + var scrapedFiles by remember { mutableStateOf>(emptyList()) } + var selectedFiles by remember { mutableStateOf>(emptySet()) } + var viewedFileContent by remember { mutableStateOf("파일을 선택하면 내용이 여기에 표시됩니다.") } + + // 앱 시작 시 파일 목록 로드 + LaunchedEffect(Unit) { + scrapedFiles = loadScrapedFiles(logMessages) + } + + MaterialTheme { + Column(modifier = Modifier.fillMaxSize()) { + // --- 전역 설정 (체크박스) --- + Row( + modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Checkbox( + checked = isBrowserVisible, + onCheckedChange = { isBrowserVisible = it } + ) + Text("브라우저 화면 보기", modifier = Modifier.clickable { isBrowserVisible = !isBrowserVisible }) + } + Divider() + + TabRow(selectedTabIndex = tabIndex) { + tabs.forEachIndexed { index, title -> + Tab(text = { Text(title) }, selected = tabIndex == index, onClick = { tabIndex = index }) + } + } + + when (tabIndex) { + 0 -> WorkflowTab( + isLoading = isLoading, + keywords = keywords, + searchResults = searchResults, + scrapedFiles = scrapedFiles, + selectedFiles = selectedFiles, + viewedFileContent = viewedFileContent, + userPrompt = userPrompt, + onUserPromptChange = { userPrompt = it }, + onFetchTrends = { + coroutineScope.launch(Dispatchers.IO) { + isLoading = true + keywords = fetchGoogleTrends(logMessages, isBrowserVisible) + isLoading = false + } + }, + onKeywordSelect = { keyword -> + selectedKeyword = keyword + coroutineScope.launch(Dispatchers.IO) { + isLoading = true + searchResults = searchOnGoogle(keyword, logMessages, isBrowserVisible) + isLoading = false + } + }, + onSearchResultSelect = { result -> + coroutineScope.launch(Dispatchers.IO) { + isLoading = true + val content = scrapeArticleByUrl(result.url, logMessages, isBrowserVisible) + if (!content.contains("오류 발생")) { + saveContentToFile(selectedKeyword, content, logMessages) + scrapedFiles = loadScrapedFiles(logMessages) // 저장 후 목록 새로고침 + } + isLoading = false + } + }, + onRefreshFiles = { + coroutineScope.launch(Dispatchers.IO) { + scrapedFiles = loadScrapedFiles(logMessages) + } + }, + onFileSelectToggle = { file, isSelected -> + selectedFiles = if (isSelected) { + selectedFiles + file + } else { + selectedFiles - file + } + }, + onFileView = { file -> + coroutineScope.launch(Dispatchers.IO) { + try { + viewedFileContent = Path(file.absolutePath).readText(Charsets.UTF_8) + } catch (e: Exception) { + logMessage(logMessages, "❌ 파일 읽기 오류: ${e.message}") + viewedFileContent = "파일을 읽는 중 오류가 발생했습니다." + } + } + }, + onGeneratePost = { + if (selectedFiles.isNotEmpty()) { + coroutineScope.launch(Dispatchers.IO) { + isLoading = true + val fileNames = selectedFiles.map { it.name } + blogPostResult = generateBlogPostWithLocalLLM(fileNames, userPrompt, logMessages) + tabIndex = 2 // 결과 탭으로 이동 + isLoading = false + } + } else { + logMessage(logMessages, "⚠️ 블로그 글을 생성할 파일을 선택해주세요.") + } + } + ) + 1 -> LogTab(logMessages) + 2 -> ResultTab(blogPostResult) + } + } + } +} + +@Composable +fun WorkflowTab( + isLoading: Boolean, + keywords: List, + searchResults: List, + scrapedFiles: List, + selectedFiles: Set, + viewedFileContent: String, + userPrompt: String, + onUserPromptChange: (String) -> Unit, + onFetchTrends: () -> Unit, + onKeywordSelect: (String) -> Unit, + onSearchResultSelect: (SearchResult) -> Unit, + onRefreshFiles: () -> Unit, + onFileSelectToggle: (File, Boolean) -> Unit, + onFileView: (File) -> Unit, + onGeneratePost: () -> Unit +) { + Box(modifier = Modifier.fillMaxSize()) { + Row(modifier = Modifier.fillMaxSize()) { + // 1열: 트렌드 키워드 + Column(modifier = Modifier.weight(1f).border(1.dp, Color.LightGray).padding(4.dp)) { + Button(onClick = onFetchTrends, modifier = Modifier.fillMaxWidth(), enabled = !isLoading) { + Text("트렌드 가져오기") + } + LazyColumn(modifier = Modifier.fillMaxSize()) { + items(keywords) { keyword -> + Text(keyword, modifier = Modifier.fillMaxWidth().clickable { if (!isLoading) onKeywordSelect(keyword) }.padding(8.dp)) + } + } + } + // 2열: 검색 결과 + Column(modifier = Modifier.weight(1.5f).border(1.dp, Color.LightGray).padding(4.dp)) { + Text("검색 결과", style = MaterialTheme.typography.h6, modifier = Modifier.padding(4.dp)) + LazyColumn(modifier = Modifier.fillMaxSize()) { + items(searchResults) { result -> + Column(modifier = Modifier.fillMaxWidth().clickable { if (!isLoading) onSearchResultSelect(result) }.padding(8.dp)) { + Text(result.title, style = MaterialTheme.typography.subtitle1, color = MaterialTheme.colors.primary) + Text(result.url, style = MaterialTheme.typography.caption, maxLines = 1) + } + } + } + } + // 3열: 스크랩된 파일 목록 + Column(modifier = Modifier.weight(1.5f).border(1.dp, Color.LightGray).padding(4.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text("저장된 파일", style = MaterialTheme.typography.h6, modifier = Modifier.weight(1f).padding(4.dp)) + Button(onClick = onRefreshFiles, enabled = !isLoading) { Text("새로고침") } + } + LazyColumn(modifier = Modifier.fillMaxSize()) { + items(scrapedFiles) { file -> + Row( + modifier = Modifier.fillMaxWidth().clickable { if (!isLoading) onFileView(file) }.padding(vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Checkbox( + checked = file in selectedFiles, + onCheckedChange = { isChecked -> onFileSelectToggle(file, isChecked) }, + enabled = !isLoading + ) + Text(file.name, modifier = Modifier.padding(start = 4.dp), maxLines = 1) + } + } + } + } + // 4열: 내용 확인 및 생성 + Column(modifier = Modifier.weight(2f).border(1.dp, Color.LightGray).padding(8.dp)) { + Text("파일 내용", style = MaterialTheme.typography.h6) + Text( + text = viewedFileContent, + modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).border(1.dp, Color.LightGray).padding(4.dp), + style = MaterialTheme.typography.body2 + ) + Spacer(Modifier.height(8.dp)) + Text("LLM 요청사항", style = MaterialTheme.typography.h6) + TextField( + value = userPrompt, + onValueChange = onUserPromptChange, + modifier = Modifier.fillMaxWidth().height(100.dp), + placeholder = { Text("예: 선택된 파일들을 종합해서...") } + ) + Spacer(Modifier.height(8.dp)) + Button(onClick = onGeneratePost, enabled = !isLoading && selectedFiles.isNotEmpty(), modifier = Modifier.fillMaxWidth()) { + Text("블로그 글 생성하기 (${selectedFiles.size}개 파일)") + } + } + } + if (isLoading) { + CircularProgressIndicator(modifier = Modifier.align(Alignment.Center)) + } + } +} + +@Composable +fun LogTab(logs: List) { + TextField( + value = logs.joinToString("\n"), + onValueChange = {}, + readOnly = true, + modifier = Modifier.fillMaxSize().padding(8.dp) + ) +} + +@Composable +fun ResultTab(result: String) { + Column(modifier = Modifier.fillMaxSize().padding(16.dp).verticalScroll(rememberScrollState())) { + Text(result) + } +} + +// --- 애플리케이션 시작점 --- + +fun main() = application { + Window( + onCloseRequest = { + httpClient.close() + exitApplication() + }, + title = "자동 블로그 포스팅 도우미 v2.6" + ) { + App() + } +} \ No newline at end of file