Update app.py
Browse files
app.py
CHANGED
|
@@ -6,11 +6,12 @@ from io import BytesIO
|
|
| 6 |
from PIL import Image
|
| 7 |
|
| 8 |
import streamlit as st
|
| 9 |
-
from openai import OpenAI
|
| 10 |
|
| 11 |
from gradio_client import Client
|
| 12 |
import pandas as pd
|
| 13 |
import PyPDF2 # For handling PDF files
|
|
|
|
| 14 |
|
| 15 |
# ββββββββββββββββββββββββββββββββ Environment Variables / Constants βββββββββββββββββββββββββ
|
| 16 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
|
|
@@ -20,28 +21,32 @@ BRAVE_VIDEO_ENDPOINT = "https://api.search.brave.com/res/v1/videos/search"
|
|
| 20 |
BRAVE_NEWS_ENDPOINT = "https://api.search.brave.com/res/v1/news/search"
|
| 21 |
IMAGE_API_URL = "http://211.233.58.201:7896"
|
| 22 |
MAX_TOKENS = 7999
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
}
|
| 32 |
|
| 33 |
RESPONSE_STYLES = {
|
| 34 |
-
"professional": "
|
| 35 |
-
"
|
| 36 |
-
"
|
| 37 |
-
"
|
| 38 |
}
|
| 39 |
|
| 40 |
# Example search queries
|
| 41 |
EXAMPLE_QUERIES = {
|
| 42 |
-
"example1": "
|
| 43 |
-
"example2": "
|
| 44 |
-
"example3": "
|
| 45 |
}
|
| 46 |
|
| 47 |
# ββββββββββββββββββββββββββββββββ Logging ββββββββββββββββββββββββββββββββ
|
|
@@ -60,105 +65,289 @@ def get_openai_client():
|
|
| 60 |
timeout=60.0,
|
| 61 |
max_retries=3
|
| 62 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
# ββββββββββββββββββββββββββββββββ System Prompt βββββββββββββββββββββββββ
|
| 65 |
-
def get_system_prompt(mode="
|
| 66 |
"""
|
| 67 |
-
Generate a system prompt for the '
|
| 68 |
-
- The selected
|
| 69 |
-
- Guidelines for using web search results and uploaded files
|
| 70 |
"""
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
1.
|
| 76 |
-
2.
|
| 77 |
-
3.
|
| 78 |
-
4.
|
| 79 |
-
5.
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
-
|
| 83 |
-
-
|
| 84 |
-
-
|
| 85 |
-
-
|
| 86 |
-
-
|
| 87 |
-
- Format your response using markdown for readability
|
| 88 |
"""
|
| 89 |
|
| 90 |
mode_prompts = {
|
| 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 |
style_guides = {
|
| 126 |
-
"professional": "
|
| 127 |
-
"
|
| 128 |
-
"
|
| 129 |
-
"
|
| 130 |
}
|
| 131 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
search_guide = """
|
| 133 |
-
|
| 134 |
-
-
|
| 135 |
-
-
|
| 136 |
-
-
|
| 137 |
-
-
|
| 138 |
-
-
|
| 139 |
-
-
|
|
|
|
| 140 |
"""
|
| 141 |
|
| 142 |
upload_guide = """
|
| 143 |
-
|
| 144 |
-
-
|
| 145 |
-
-
|
| 146 |
-
-
|
| 147 |
-
-
|
| 148 |
-
-
|
| 149 |
-
-
|
| 150 |
-
-
|
| 151 |
"""
|
| 152 |
|
| 153 |
# Base prompt
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
|
|
|
| 158 |
|
| 159 |
# Style
|
| 160 |
if style in style_guides:
|
| 161 |
-
final_prompt += f"\n\
|
|
|
|
|
|
|
|
|
|
| 162 |
|
| 163 |
if include_search_results:
|
| 164 |
final_prompt += f"\n\n{search_guide}"
|
|
@@ -167,23 +356,24 @@ Guidelines for Using Uploaded Files:
|
|
| 167 |
final_prompt += f"\n\n{upload_guide}"
|
| 168 |
|
| 169 |
final_prompt += """
|
| 170 |
-
\n\
|
| 171 |
-
-
|
| 172 |
-
-
|
| 173 |
-
-
|
| 174 |
-
-
|
| 175 |
-
-
|
|
|
|
| 176 |
"""
|
| 177 |
return final_prompt
|
| 178 |
|
| 179 |
# ββββββββββββββββββββββββββββββββ Brave Search API ββββββββββββββββββββββββ
|
| 180 |
@st.cache_data(ttl=3600)
|
| 181 |
-
def brave_search(query: str, count: int =
|
| 182 |
if not BRAVE_KEY:
|
| 183 |
raise RuntimeError("β οΈ SERPHOUSE_API_KEY (Brave API Key) environment variable is empty.")
|
| 184 |
|
| 185 |
headers = {"Accept": "application/json", "Accept-Encoding": "gzip", "X-Subscription-Token": BRAVE_KEY}
|
| 186 |
-
params = {"q": query, "count": str(count)}
|
| 187 |
|
| 188 |
for attempt in range(3):
|
| 189 |
try:
|
|
@@ -221,12 +411,12 @@ def brave_search(query: str, count: int = 20):
|
|
| 221 |
return []
|
| 222 |
|
| 223 |
@st.cache_data(ttl=3600)
|
| 224 |
-
def brave_video_search(query: str, count: int =
|
| 225 |
if not BRAVE_KEY:
|
| 226 |
raise RuntimeError("β οΈ SERPHOUSE_API_KEY (Brave API Key) environment variable is empty.")
|
| 227 |
|
| 228 |
headers = {"Accept": "application/json","Accept-Encoding": "gzip","X-Subscription-Token": BRAVE_KEY}
|
| 229 |
-
params = {"q": query, "count": str(count)}
|
| 230 |
|
| 231 |
for attempt in range(3):
|
| 232 |
try:
|
|
@@ -255,12 +445,12 @@ def brave_video_search(query: str, count: int = 5):
|
|
| 255 |
return []
|
| 256 |
|
| 257 |
@st.cache_data(ttl=3600)
|
| 258 |
-
def brave_news_search(query: str, count: int =
|
| 259 |
if not BRAVE_KEY:
|
| 260 |
raise RuntimeError("β οΈ SERPHOUSE_API_KEY (Brave API Key) environment variable is empty.")
|
| 261 |
|
| 262 |
headers = {"Accept": "application/json","Accept-Encoding": "gzip","X-Subscription-Token": BRAVE_KEY}
|
| 263 |
-
params = {"q": query, "count": str(count)}
|
| 264 |
|
| 265 |
for attempt in range(3):
|
| 266 |
try:
|
|
@@ -291,19 +481,19 @@ def brave_news_search(query: str, count: int = 5):
|
|
| 291 |
|
| 292 |
def mock_results(query: str) -> str:
|
| 293 |
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 294 |
-
return (f"#
|
| 295 |
-
f"
|
| 296 |
-
f"
|
| 297 |
-
f"
|
| 298 |
-
f"-
|
| 299 |
-
f"-
|
| 300 |
-
f"-
|
| 301 |
-
f"-
|
| 302 |
-
f"
|
| 303 |
|
| 304 |
def do_web_search(query: str) -> str:
|
| 305 |
try:
|
| 306 |
-
arts = brave_search(query,
|
| 307 |
if not arts:
|
| 308 |
logging.warning("No search results, using fallback content")
|
| 309 |
return mock_results(query)
|
|
@@ -311,26 +501,26 @@ def do_web_search(query: str) -> str:
|
|
| 311 |
videos = brave_video_search(query, 2)
|
| 312 |
news = brave_news_search(query, 3)
|
| 313 |
|
| 314 |
-
result = "#
|
| 315 |
|
| 316 |
-
result += "##
|
| 317 |
-
for a in arts[:
|
| 318 |
-
result += f"###
|
| 319 |
-
result += f"
|
| 320 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 321 |
if videos:
|
| 322 |
-
result += "##
|
| 323 |
for vid in videos:
|
| 324 |
result += f"### {vid['title']}\n\n"
|
| 325 |
if vid.get('thumbnail_url'):
|
| 326 |
-
result += f"![
|
| 327 |
-
result += f"
|
| 328 |
-
|
| 329 |
-
if news:
|
| 330 |
-
result += "## News Results\n\n"
|
| 331 |
-
for n in news:
|
| 332 |
-
result += f"### {n['title']}\n\n{n['description']}\n\n"
|
| 333 |
-
result += f"**Source**: [{n['source']}]({n['url']}) - {n['date']}\n\n---\n"
|
| 334 |
|
| 335 |
return result
|
| 336 |
|
|
@@ -348,11 +538,11 @@ def process_text_file(file):
|
|
| 348 |
if len(text) > 10000:
|
| 349 |
text = text[:9700] + "...(truncated)..."
|
| 350 |
|
| 351 |
-
result = f"##
|
| 352 |
return result
|
| 353 |
except Exception as e:
|
| 354 |
logging.error(f"Error processing text file: {str(e)}")
|
| 355 |
-
return f"
|
| 356 |
|
| 357 |
def process_csv_file(file):
|
| 358 |
try:
|
|
@@ -360,41 +550,41 @@ def process_csv_file(file):
|
|
| 360 |
file.seek(0)
|
| 361 |
|
| 362 |
df = pd.read_csv(io.BytesIO(content))
|
| 363 |
-
result = f"## CSV
|
| 364 |
-
result += f"-
|
| 365 |
-
result += f"-
|
| 366 |
-
result += f"-
|
| 367 |
|
| 368 |
-
result += "###
|
| 369 |
preview_df = df.head(10)
|
| 370 |
try:
|
| 371 |
markdown_table = preview_df.to_markdown(index=False)
|
| 372 |
if markdown_table:
|
| 373 |
result += markdown_table + "\n\n"
|
| 374 |
else:
|
| 375 |
-
result += "
|
| 376 |
except Exception as e:
|
| 377 |
logging.error(f"Markdown table conversion error: {e}")
|
| 378 |
-
result += "
|
| 379 |
|
| 380 |
num_cols = df.select_dtypes(include=['number']).columns
|
| 381 |
if len(num_cols) > 0:
|
| 382 |
-
result += "###
|
| 383 |
try:
|
| 384 |
stats_df = df[num_cols].describe().round(2)
|
| 385 |
stats_markdown = stats_df.to_markdown()
|
| 386 |
if stats_markdown:
|
| 387 |
result += stats_markdown + "\n\n"
|
| 388 |
else:
|
| 389 |
-
result += "
|
| 390 |
except Exception as e:
|
| 391 |
logging.error(f"Statistical info conversion error: {e}")
|
| 392 |
-
result += "
|
| 393 |
|
| 394 |
return result
|
| 395 |
except Exception as e:
|
| 396 |
logging.error(f"CSV file processing error: {str(e)}")
|
| 397 |
-
return f"
|
| 398 |
|
| 399 |
def process_pdf_file(file):
|
| 400 |
try:
|
|
@@ -404,7 +594,7 @@ def process_pdf_file(file):
|
|
| 404 |
pdf_file = io.BytesIO(file_bytes)
|
| 405 |
reader = PyPDF2.PdfReader(pdf_file, strict=False)
|
| 406 |
|
| 407 |
-
result = f"## PDF
|
| 408 |
|
| 409 |
max_pages = min(5, len(reader.pages))
|
| 410 |
all_text = ""
|
|
@@ -413,40 +603,40 @@ def process_pdf_file(file):
|
|
| 413 |
try:
|
| 414 |
page = reader.pages[i]
|
| 415 |
page_text = page.extract_text()
|
| 416 |
-
current_page_text = f"###
|
| 417 |
if page_text and len(page_text.strip()) > 0:
|
| 418 |
if len(page_text) > 1500:
|
| 419 |
-
current_page_text += page_text[:1500] + "...(
|
| 420 |
else:
|
| 421 |
current_page_text += page_text + "\n\n"
|
| 422 |
else:
|
| 423 |
-
current_page_text += "(
|
| 424 |
|
| 425 |
all_text += current_page_text
|
| 426 |
|
| 427 |
if len(all_text) > 8000:
|
| 428 |
-
all_text += "...(
|
| 429 |
break
|
| 430 |
|
| 431 |
except Exception as page_err:
|
| 432 |
logging.error(f"Error processing PDF page {i+1}: {str(page_err)}")
|
| 433 |
-
all_text += f"###
|
| 434 |
|
| 435 |
if len(reader.pages) > max_pages:
|
| 436 |
-
all_text += f"\
|
| 437 |
|
| 438 |
-
result += "### PDF
|
| 439 |
return result
|
| 440 |
|
| 441 |
except Exception as e:
|
| 442 |
logging.error(f"PDF file processing error: {str(e)}")
|
| 443 |
-
return f"## PDF
|
| 444 |
|
| 445 |
def process_uploaded_files(files):
|
| 446 |
if not files:
|
| 447 |
return None
|
| 448 |
|
| 449 |
-
result = "#
|
| 450 |
for file in files:
|
| 451 |
try:
|
| 452 |
ext = file.name.split('.')[-1].lower()
|
|
@@ -457,10 +647,10 @@ def process_uploaded_files(files):
|
|
| 457 |
elif ext == 'pdf':
|
| 458 |
result += process_pdf_file(file) + "\n\n---\n\n"
|
| 459 |
else:
|
| 460 |
-
result += f"###
|
| 461 |
except Exception as e:
|
| 462 |
logging.error(f"File processing error {file.name}: {e}")
|
| 463 |
-
result += f"###
|
| 464 |
|
| 465 |
return result
|
| 466 |
|
|
@@ -488,8 +678,8 @@ def extract_image_prompt(response_text: str, topic: str):
|
|
| 488 |
response = client.chat.completions.create(
|
| 489 |
model="gpt-4.1-mini",
|
| 490 |
messages=[
|
| 491 |
-
{"role": "system", "content": "
|
| 492 |
-
{"role": "user", "content": f"
|
| 493 |
],
|
| 494 |
temperature=1,
|
| 495 |
max_tokens=80,
|
|
@@ -498,9 +688,9 @@ def extract_image_prompt(response_text: str, topic: str):
|
|
| 498 |
return response.choices[0].message.content.strip()
|
| 499 |
except Exception as e:
|
| 500 |
logging.error(f"OpenAI image prompt generation error: {e}")
|
| 501 |
-
return f"A professional
|
| 502 |
|
| 503 |
-
def md_to_html(md: str, title="
|
| 504 |
return f"<!DOCTYPE html><html><head><title>{title}</title><meta charset='utf-8'></head><body>{markdown.markdown(md)}</body></html>"
|
| 505 |
|
| 506 |
def keywords(text: str, top=5):
|
|
@@ -508,8 +698,9 @@ def keywords(text: str, top=5):
|
|
| 508 |
return " ".join(cleaned.split()[:top])
|
| 509 |
|
| 510 |
# ββββββββββββββββββββββββββββββββ Streamlit UI ββββββββββββββββββββββββββββ
|
| 511 |
-
def
|
| 512 |
-
st.title("
|
|
|
|
| 513 |
|
| 514 |
if "ai_model" not in st.session_state:
|
| 515 |
st.session_state.ai_model = "gpt-4.1-mini"
|
|
@@ -521,48 +712,61 @@ def perplexity_app():
|
|
| 521 |
st.session_state.generate_image = False
|
| 522 |
if "web_search_enabled" not in st.session_state:
|
| 523 |
st.session_state.web_search_enabled = True
|
| 524 |
-
if "
|
| 525 |
-
st.session_state.
|
| 526 |
if "response_style" not in st.session_state:
|
| 527 |
st.session_state.response_style = "professional"
|
| 528 |
|
| 529 |
sb = st.sidebar
|
| 530 |
-
sb.title("
|
| 531 |
|
| 532 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 533 |
sb.selectbox(
|
| 534 |
-
"
|
| 535 |
-
options=list(
|
| 536 |
-
format_func=lambda x:
|
| 537 |
-
key="
|
| 538 |
)
|
| 539 |
|
| 540 |
sb.selectbox(
|
| 541 |
-
"
|
| 542 |
options=list(RESPONSE_STYLES.keys()),
|
| 543 |
format_func=lambda x: RESPONSE_STYLES[x],
|
| 544 |
key="response_style"
|
| 545 |
)
|
| 546 |
|
| 547 |
# Example queries
|
| 548 |
-
sb.subheader("
|
| 549 |
c1, c2, c3 = sb.columns(3)
|
| 550 |
-
if c1.button("
|
| 551 |
process_example(EXAMPLE_QUERIES["example1"])
|
| 552 |
-
if c2.button("
|
| 553 |
process_example(EXAMPLE_QUERIES["example2"])
|
| 554 |
-
if c3.button("
|
| 555 |
process_example(EXAMPLE_QUERIES["example3"])
|
| 556 |
|
| 557 |
-
sb.subheader("
|
| 558 |
-
sb.toggle("
|
| 559 |
-
sb.toggle("
|
| 560 |
|
| 561 |
-
web_search_enabled = sb.toggle("
|
| 562 |
st.session_state.web_search_enabled = web_search_enabled
|
| 563 |
|
| 564 |
if web_search_enabled:
|
| 565 |
-
st.sidebar.info("β
|
| 566 |
|
| 567 |
# Download the latest response
|
| 568 |
latest_response = next(
|
|
@@ -578,35 +782,35 @@ def perplexity_app():
|
|
| 578 |
first_line = latest_response.split('\n', 1)[0].strip()
|
| 579 |
title = first_line[:40] + "..." if len(first_line) > 40 else first_line
|
| 580 |
|
| 581 |
-
sb.subheader("
|
| 582 |
d1, d2 = sb.columns(2)
|
| 583 |
-
d1.download_button("
|
| 584 |
file_name=f"{title}.md", mime="text/markdown")
|
| 585 |
-
d2.download_button("
|
| 586 |
file_name=f"{title}.html", mime="text/html")
|
| 587 |
|
| 588 |
# JSON conversation record upload
|
| 589 |
-
up = sb.file_uploader("
|
| 590 |
if up:
|
| 591 |
try:
|
| 592 |
st.session_state.messages = json.load(up)
|
| 593 |
-
sb.success("
|
| 594 |
except Exception as e:
|
| 595 |
-
sb.error(f"
|
| 596 |
|
| 597 |
# JSON conversation record download
|
| 598 |
-
if sb.button("
|
| 599 |
sb.download_button(
|
| 600 |
-
"
|
| 601 |
data=json.dumps(st.session_state.messages, ensure_ascii=False, indent=2),
|
| 602 |
file_name="conversation_history.json",
|
| 603 |
mime="application/json"
|
| 604 |
)
|
| 605 |
|
| 606 |
# File Upload
|
| 607 |
-
st.subheader("
|
| 608 |
uploaded_files = st.file_uploader(
|
| 609 |
-
"
|
| 610 |
type=["txt", "csv", "pdf"],
|
| 611 |
accept_multiple_files=True,
|
| 612 |
key="file_uploader"
|
|
@@ -614,18 +818,18 @@ def perplexity_app():
|
|
| 614 |
|
| 615 |
if uploaded_files:
|
| 616 |
file_count = len(uploaded_files)
|
| 617 |
-
st.success(f"{file_count}
|
| 618 |
|
| 619 |
-
with st.expander("
|
| 620 |
for idx, file in enumerate(uploaded_files):
|
| 621 |
-
st.write(f"
|
| 622 |
ext = file.name.split('.')[-1].lower()
|
| 623 |
|
| 624 |
if ext == 'txt':
|
| 625 |
preview = file.read(1000).decode('utf-8', errors='ignore')
|
| 626 |
file.seek(0)
|
| 627 |
st.text_area(
|
| 628 |
-
f"
|
| 629 |
preview + ("..." if len(preview) >= 1000 else ""),
|
| 630 |
height=150
|
| 631 |
)
|
|
@@ -633,10 +837,10 @@ def perplexity_app():
|
|
| 633 |
try:
|
| 634 |
df = pd.read_csv(file)
|
| 635 |
file.seek(0)
|
| 636 |
-
st.write("CSV
|
| 637 |
st.dataframe(df.head(5))
|
| 638 |
except Exception as e:
|
| 639 |
-
st.error(f"CSV
|
| 640 |
elif ext == 'pdf':
|
| 641 |
try:
|
| 642 |
file_bytes = file.read()
|
|
@@ -646,17 +850,17 @@ def perplexity_app():
|
|
| 646 |
reader = PyPDF2.PdfReader(pdf_file, strict=False)
|
| 647 |
|
| 648 |
pc = len(reader.pages)
|
| 649 |
-
st.write(f"PDF
|
| 650 |
|
| 651 |
if pc > 0:
|
| 652 |
try:
|
| 653 |
page_text = reader.pages[0].extract_text()
|
| 654 |
-
preview = page_text[:500] if page_text else "(
|
| 655 |
-
st.text_area("
|
| 656 |
except:
|
| 657 |
-
st.warning("
|
| 658 |
except Exception as e:
|
| 659 |
-
st.error(f"PDF
|
| 660 |
|
| 661 |
if idx < file_count - 1:
|
| 662 |
st.divider()
|
|
@@ -668,9 +872,9 @@ def perplexity_app():
|
|
| 668 |
|
| 669 |
# Videos
|
| 670 |
if "videos" in m and m["videos"]:
|
| 671 |
-
st.subheader("
|
| 672 |
for video in m["videos"]:
|
| 673 |
-
video_title = video.get('title', '
|
| 674 |
video_url = video.get('url', '')
|
| 675 |
thumbnail = video.get('thumbnail', '')
|
| 676 |
|
|
@@ -680,13 +884,13 @@ def perplexity_app():
|
|
| 680 |
st.write("π¬")
|
| 681 |
with col2:
|
| 682 |
st.markdown(f"**[{video_title}]({video_url})**")
|
| 683 |
-
st.write(f"
|
| 684 |
else:
|
| 685 |
st.markdown(f"π¬ **[{video_title}]({video_url})**")
|
| 686 |
-
st.write(f"
|
| 687 |
|
| 688 |
# User input
|
| 689 |
-
query = st.chat_input("
|
| 690 |
if query:
|
| 691 |
process_input(query, uploaded_files)
|
| 692 |
|
|
@@ -712,8 +916,8 @@ def process_input(query: str, uploaded_files):
|
|
| 712 |
has_uploaded_files = bool(uploaded_files) and len(uploaded_files) > 0
|
| 713 |
|
| 714 |
try:
|
| 715 |
-
status = st.status("
|
| 716 |
-
status.update(label="
|
| 717 |
|
| 718 |
client = get_openai_client()
|
| 719 |
|
|
@@ -721,22 +925,27 @@ def process_input(query: str, uploaded_files):
|
|
| 721 |
video_results = []
|
| 722 |
news_results = []
|
| 723 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 724 |
if use_web_search:
|
| 725 |
-
status.update(label="
|
| 726 |
-
with st.spinner("
|
| 727 |
search_content = do_web_search(keywords(query, top=5))
|
| 728 |
|
| 729 |
try:
|
| 730 |
-
status.update(label="
|
| 731 |
video_results = brave_video_search(query, 2)
|
| 732 |
news_results = brave_news_search(query, 3)
|
| 733 |
except Exception as search_err:
|
| 734 |
-
logging.error(f"
|
| 735 |
|
| 736 |
file_content = None
|
| 737 |
if has_uploaded_files:
|
| 738 |
-
status.update(label="
|
| 739 |
-
with st.spinner("
|
| 740 |
file_content = process_uploaded_files(uploaded_files)
|
| 741 |
|
| 742 |
valid_videos = []
|
|
@@ -745,14 +954,14 @@ def process_input(query: str, uploaded_files):
|
|
| 745 |
if url and url.startswith('http'):
|
| 746 |
valid_videos.append({
|
| 747 |
'url': url,
|
| 748 |
-
'title': vid.get('title', '
|
| 749 |
'thumbnail': vid.get('thumbnail_url', ''),
|
| 750 |
-
'source': vid.get('source', '
|
| 751 |
})
|
| 752 |
|
| 753 |
-
status.update(label="
|
| 754 |
sys_prompt = get_system_prompt(
|
| 755 |
-
mode=st.session_state.
|
| 756 |
style=st.session_state.response_style,
|
| 757 |
include_search_results=use_web_search,
|
| 758 |
include_uploaded_files=has_uploaded_files
|
|
@@ -763,13 +972,16 @@ def process_input(query: str, uploaded_files):
|
|
| 763 |
]
|
| 764 |
|
| 765 |
user_content = query
|
|
|
|
|
|
|
|
|
|
| 766 |
if search_content:
|
| 767 |
user_content += "\n\n" + search_content
|
| 768 |
if file_content:
|
| 769 |
user_content += "\n\n" + file_content
|
| 770 |
|
| 771 |
if valid_videos:
|
| 772 |
-
user_content += "\n\n#
|
| 773 |
for i, vid in enumerate(valid_videos):
|
| 774 |
user_content += f"\n{i+1}. **{vid['title']}** - [{vid['source']}]({vid['url']})\n"
|
| 775 |
|
|
@@ -794,15 +1006,15 @@ def process_input(query: str, uploaded_files):
|
|
| 794 |
message_placeholder.markdown(full_response, unsafe_allow_html=True)
|
| 795 |
|
| 796 |
if valid_videos:
|
| 797 |
-
st.subheader("
|
| 798 |
for video in valid_videos:
|
| 799 |
-
video_title = video.get('title', '
|
| 800 |
video_url = video.get('url', '')
|
| 801 |
|
| 802 |
st.markdown(f"π¬ **[{video_title}]({video_url})**")
|
| 803 |
-
st.write(f"
|
| 804 |
|
| 805 |
-
status.update(label="
|
| 806 |
|
| 807 |
st.session_state.messages.append({
|
| 808 |
"role": "assistant",
|
|
@@ -812,27 +1024,27 @@ def process_input(query: str, uploaded_files):
|
|
| 812 |
|
| 813 |
except Exception as api_error:
|
| 814 |
error_message = str(api_error)
|
| 815 |
-
logging.error(f"API
|
| 816 |
-
status.update(label=f"
|
| 817 |
-
raise Exception(f"
|
| 818 |
|
| 819 |
if st.session_state.generate_image and full_response:
|
| 820 |
-
with st.spinner("
|
| 821 |
try:
|
| 822 |
ip = extract_image_prompt(full_response, query)
|
| 823 |
img, cap = generate_image(ip)
|
| 824 |
if img:
|
| 825 |
-
st.subheader("AI
|
| 826 |
st.image(img, caption=cap, use_container_width=True)
|
| 827 |
except Exception as img_error:
|
| 828 |
-
logging.error(f"
|
| 829 |
-
st.warning("
|
| 830 |
|
| 831 |
if full_response:
|
| 832 |
-
st.subheader("
|
| 833 |
c1, c2 = st.columns(2)
|
| 834 |
c1.download_button(
|
| 835 |
-
"
|
| 836 |
data=full_response,
|
| 837 |
file_name=f"{query[:30]}.md",
|
| 838 |
mime="text/markdown"
|
|
@@ -850,19 +1062,19 @@ def process_input(query: str, uploaded_files):
|
|
| 850 |
with open(fn, "w", encoding="utf-8") as fp:
|
| 851 |
json.dump(st.session_state.messages, fp, ensure_ascii=False, indent=2)
|
| 852 |
except Exception as e:
|
| 853 |
-
logging.error(f"
|
| 854 |
|
| 855 |
except Exception as e:
|
| 856 |
error_message = str(e)
|
| 857 |
-
placeholder.error(f"
|
| 858 |
-
logging.error(f"
|
| 859 |
-
ans = f"
|
| 860 |
st.session_state.messages.append({"role": "assistant", "content": ans})
|
| 861 |
|
| 862 |
# ββββββββββββββββββββββββββββββββ main ββββββββββββββββββββββββββββββββββββ
|
| 863 |
def main():
|
| 864 |
-
st.write("====
|
| 865 |
-
|
| 866 |
|
| 867 |
if __name__ == "__main__":
|
| 868 |
main()
|
|
|
|
| 6 |
from PIL import Image
|
| 7 |
|
| 8 |
import streamlit as st
|
| 9 |
+
from openai import OpenAI
|
| 10 |
|
| 11 |
from gradio_client import Client
|
| 12 |
import pandas as pd
|
| 13 |
import PyPDF2 # For handling PDF files
|
| 14 |
+
import kagglehub
|
| 15 |
|
| 16 |
# ββββββββββββββββββββββββββββββββ Environment Variables / Constants βββββββββββββββββββββββββ
|
| 17 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
|
|
|
|
| 21 |
BRAVE_NEWS_ENDPOINT = "https://api.search.brave.com/res/v1/news/search"
|
| 22 |
IMAGE_API_URL = "http://211.233.58.201:7896"
|
| 23 |
MAX_TOKENS = 7999
|
| 24 |
+
KAGGLE_API_KEY = os.getenv("KDATA_API", "")
|
| 25 |
+
|
| 26 |
+
# Set Kaggle API key
|
| 27 |
+
os.environ["KAGGLE_KEY"] = KAGGLE_API_KEY
|
| 28 |
+
|
| 29 |
+
# Analysis modes and style definitions
|
| 30 |
+
ANALYSIS_MODES = {
|
| 31 |
+
"price_forecast": "λμ°λ¬Ό κ°κ²© μμΈ‘κ³Ό μμ₯ λΆμ",
|
| 32 |
+
"market_trend": "μμ₯ λν₯ λ° μμ ν¨ν΄ λΆμ",
|
| 33 |
+
"production_analysis": "μμ°λ λΆμ λ° μλ μ보 μ λ§",
|
| 34 |
+
"agricultural_policy": "λμ
μ μ±
λ° κ·μ μν₯ λΆμ",
|
| 35 |
+
"climate_impact": "κΈ°ν λ³νκ° λμ
μ λ―ΈμΉλ μν₯ λΆμ"
|
| 36 |
}
|
| 37 |
|
| 38 |
RESPONSE_STYLES = {
|
| 39 |
+
"professional": "μ λ¬Έμ μ΄κ³ νμ μ μΈ λΆμ",
|
| 40 |
+
"simple": "μ½κ² μ΄ν΄ν μ μλ κ°κ²°ν μ€λͺ
",
|
| 41 |
+
"detailed": "μμΈν ν΅κ³ κΈ°λ° κΉμ΄ μλ λΆμ",
|
| 42 |
+
"action_oriented": "μ€ν κ°λ₯ν μ‘°μΈκ³Ό μΆμ² μ€μ¬"
|
| 43 |
}
|
| 44 |
|
| 45 |
# Example search queries
|
| 46 |
EXAMPLE_QUERIES = {
|
| 47 |
+
"example1": "μ κ°κ²© μΆμΈ λ° ν₯ν 6κ°μ μ λ§μ λΆμν΄μ£ΌμΈμ",
|
| 48 |
+
"example2": "κΈ°ν λ³νλ νκ΅ μ±μ μμ°μ μ΄λ€ μν₯μ λ―ΈμΉλμ?",
|
| 49 |
+
"example3": "μΈκ³ 곑물 μμ₯ λν₯κ³Ό κ΅λ΄ μλ μ보μ λ―ΈμΉλ μν₯μ?"
|
| 50 |
}
|
| 51 |
|
| 52 |
# ββββββββββββββββββββββββββββββββ Logging ββββββββββββββββββββββββββββββββ
|
|
|
|
| 65 |
timeout=60.0,
|
| 66 |
max_retries=3
|
| 67 |
)
|
| 68 |
+
|
| 69 |
+
# ββββββββββββββββββββββββββββββ Kaggle Dataset Access ββββββββββββββββββββββ
|
| 70 |
+
@st.cache_resource
|
| 71 |
+
def load_agriculture_dataset():
|
| 72 |
+
"""Download and load the UN agriculture dataset from Kaggle"""
|
| 73 |
+
try:
|
| 74 |
+
path = kagglehub.dataset_download("unitednations/global-food-agriculture-statistics")
|
| 75 |
+
logging.info(f"Kaggle dataset downloaded to: {path}")
|
| 76 |
+
|
| 77 |
+
# Load metadata about available files
|
| 78 |
+
available_files = []
|
| 79 |
+
for root, dirs, files in os.walk(path):
|
| 80 |
+
for file in files:
|
| 81 |
+
if file.endswith('.csv'):
|
| 82 |
+
file_path = os.path.join(root, file)
|
| 83 |
+
file_size = os.path.getsize(file_path) / (1024 * 1024) # Size in MB
|
| 84 |
+
available_files.append({
|
| 85 |
+
'name': file,
|
| 86 |
+
'path': file_path,
|
| 87 |
+
'size_mb': round(file_size, 2)
|
| 88 |
+
})
|
| 89 |
+
|
| 90 |
+
return {
|
| 91 |
+
'base_path': path,
|
| 92 |
+
'files': available_files
|
| 93 |
+
}
|
| 94 |
+
except Exception as e:
|
| 95 |
+
logging.error(f"Error loading Kaggle dataset: {e}")
|
| 96 |
+
return None
|
| 97 |
+
|
| 98 |
+
def get_dataset_summary():
|
| 99 |
+
"""Generate a summary of the available agriculture datasets"""
|
| 100 |
+
dataset_info = load_agriculture_dataset()
|
| 101 |
+
if not dataset_info:
|
| 102 |
+
return "Failed to load the UN global food and agriculture statistics dataset."
|
| 103 |
+
|
| 104 |
+
summary = "# UN κΈλ‘λ² μλ λ° λμ
ν΅κ³ λ°μ΄ν°μ
\n\n"
|
| 105 |
+
summary += f"μ΄ {len(dataset_info['files'])}κ°μ CSV νμΌμ΄ ν¬ν¨λμ΄ μμ΅λλ€.\n\n"
|
| 106 |
+
|
| 107 |
+
# List files with sizes
|
| 108 |
+
summary += "## μ¬μ© κ°λ₯ν λ°μ΄ν° νμΌ:\n\n"
|
| 109 |
+
for i, file_info in enumerate(dataset_info['files'][:10], 1): # Limit to first 10 files
|
| 110 |
+
summary += f"{i}. **{file_info['name']}** ({file_info['size_mb']} MB)\n"
|
| 111 |
+
|
| 112 |
+
if len(dataset_info['files']) > 10:
|
| 113 |
+
summary += f"\n...μΈ {len(dataset_info['files']) - 10}κ° νμΌ\n"
|
| 114 |
+
|
| 115 |
+
# Add example of data structure
|
| 116 |
+
try:
|
| 117 |
+
if dataset_info['files']:
|
| 118 |
+
sample_file = dataset_info['files'][0]['path']
|
| 119 |
+
df = pd.read_csv(sample_file, nrows=5)
|
| 120 |
+
summary += "\n## λ°μ΄ν° μν ꡬ쑰:\n\n"
|
| 121 |
+
summary += df.head(5).to_markdown() + "\n\n"
|
| 122 |
+
|
| 123 |
+
summary += "## λ°μ΄ν°μ
λ³μ μ€λͺ
:\n\n"
|
| 124 |
+
for col in df.columns:
|
| 125 |
+
summary += f"- **{col}**: [λ³μ μ€λͺ
νμ]\n"
|
| 126 |
+
except Exception as e:
|
| 127 |
+
logging.error(f"Error generating dataset sample: {e}")
|
| 128 |
+
summary += "\nλ°μ΄ν° μνμ μμ±νλ μ€ μ€λ₯κ° λ°μνμ΅λλ€.\n"
|
| 129 |
+
|
| 130 |
+
return summary
|
| 131 |
+
|
| 132 |
+
def analyze_dataset_for_query(query):
|
| 133 |
+
"""Find and analyze relevant data from the dataset based on the query"""
|
| 134 |
+
dataset_info = load_agriculture_dataset()
|
| 135 |
+
if not dataset_info:
|
| 136 |
+
return "λ°μ΄ν°μ
μ λΆλ¬μ¬ μ μμ΅λλ€. Kaggle API μ°κ²°μ νμΈν΄μ£ΌμΈμ."
|
| 137 |
+
|
| 138 |
+
# Extract key terms from the query
|
| 139 |
+
query_lower = query.lower()
|
| 140 |
+
|
| 141 |
+
# Define keywords to look for in the dataset files
|
| 142 |
+
keywords = {
|
| 143 |
+
"μ": ["rice", "grain"],
|
| 144 |
+
"λ°": ["wheat", "grain"],
|
| 145 |
+
"μ₯μμ": ["corn", "maize", "grain"],
|
| 146 |
+
"μ±μ": ["vegetable", "produce"],
|
| 147 |
+
"κ³ΌμΌ": ["fruit", "produce"],
|
| 148 |
+
"κ°κ²©": ["price", "cost", "value"],
|
| 149 |
+
"μμ°": ["production", "yield", "harvest"],
|
| 150 |
+
"μμΆ": ["export", "trade"],
|
| 151 |
+
"μμ
": ["import", "trade"],
|
| 152 |
+
"μλΉ": ["consumption", "demand"]
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
# Find relevant files based on the query
|
| 156 |
+
relevant_files = []
|
| 157 |
+
|
| 158 |
+
# First check for Korean keywords in the query
|
| 159 |
+
found_keywords = []
|
| 160 |
+
for k_term, e_terms in keywords.items():
|
| 161 |
+
if k_term in query_lower:
|
| 162 |
+
found_keywords.extend([k_term] + e_terms)
|
| 163 |
+
|
| 164 |
+
# If no Korean keywords found, check for English terms in the filenames
|
| 165 |
+
if not found_keywords:
|
| 166 |
+
# Generic search through all files
|
| 167 |
+
relevant_files = dataset_info['files'][:5] # Take first 5 files as default
|
| 168 |
+
else:
|
| 169 |
+
# Search for files related to the found keywords
|
| 170 |
+
for file_info in dataset_info['files']:
|
| 171 |
+
file_name_lower = file_info['name'].lower()
|
| 172 |
+
for keyword in found_keywords:
|
| 173 |
+
if keyword.lower() in file_name_lower:
|
| 174 |
+
relevant_files.append(file_info)
|
| 175 |
+
break
|
| 176 |
+
|
| 177 |
+
# If still no relevant files, take the first 5 files
|
| 178 |
+
if not relevant_files:
|
| 179 |
+
relevant_files = dataset_info['files'][:5]
|
| 180 |
+
|
| 181 |
+
# Read and analyze the relevant files
|
| 182 |
+
analysis_result = "# λμ
λ°μ΄ν° λΆμ κ²°κ³Ό\n\n"
|
| 183 |
+
analysis_result += f"쿼리: '{query}'μ λν λΆμμ μννμ΅λλ€.\n\n"
|
| 184 |
+
|
| 185 |
+
if found_keywords:
|
| 186 |
+
analysis_result += f"## λΆμ ν€μλ: {', '.join(set(found_keywords))}\n\n"
|
| 187 |
+
|
| 188 |
+
# Process each relevant file
|
| 189 |
+
for file_info in relevant_files[:3]: # Limit to 3 files for performance
|
| 190 |
+
try:
|
| 191 |
+
analysis_result += f"## νμΌ: {file_info['name']}\n\n"
|
| 192 |
+
|
| 193 |
+
# Read the CSV file
|
| 194 |
+
df = pd.read_csv(file_info['path'])
|
| 195 |
+
|
| 196 |
+
# Basic file stats
|
| 197 |
+
analysis_result += f"- ν μ: {len(df)}\n"
|
| 198 |
+
analysis_result += f"- μ΄ μ: {len(df.columns)}\n"
|
| 199 |
+
analysis_result += f"- μ΄ λͺ©λ‘: {', '.join(df.columns.tolist())}\n\n"
|
| 200 |
+
|
| 201 |
+
# Sample data
|
| 202 |
+
analysis_result += "### λ°μ΄ν° μν:\n\n"
|
| 203 |
+
analysis_result += df.head(5).to_markdown() + "\n\n"
|
| 204 |
+
|
| 205 |
+
# Statistical summary of numeric columns
|
| 206 |
+
numeric_cols = df.select_dtypes(include=['number']).columns
|
| 207 |
+
if len(numeric_cols) > 0:
|
| 208 |
+
analysis_result += "### κΈ°λ³Έ ν΅κ³:\n\n"
|
| 209 |
+
stats_df = df[numeric_cols].describe()
|
| 210 |
+
analysis_result += stats_df.to_markdown() + "\n\n"
|
| 211 |
+
|
| 212 |
+
# Time series analysis if possible
|
| 213 |
+
time_cols = [col for col in df.columns if 'year' in col.lower() or 'date' in col.lower()]
|
| 214 |
+
if time_cols:
|
| 215 |
+
analysis_result += "### μκ³μ΄ ν¨ν΄:\n\n"
|
| 216 |
+
analysis_result += "λ°μ΄ν°μ
μ μκ° κ΄λ ¨ μ΄μ΄ μμ΄ μκ³μ΄ λΆμμ΄ κ°λ₯ν©λλ€.\n\n"
|
| 217 |
+
|
| 218 |
+
except Exception as e:
|
| 219 |
+
logging.error(f"Error analyzing file {file_info['name']}: {e}")
|
| 220 |
+
analysis_result += f"μ΄ νμΌ λΆμ μ€ μ€λ₯κ° λ°μνμ΅λλ€: {str(e)}\n\n"
|
| 221 |
+
|
| 222 |
+
analysis_result += "## λμ°λ¬Ό κ°κ²© μμΈ‘ λ° μμ λΆμμ λν μΈμ¬μ΄νΈ\n\n"
|
| 223 |
+
analysis_result += "λ°μ΄ν°μ
μμ μΆμΆν μ 보λ₯Ό λ°νμΌλ‘ λ€μ μΈμ¬μ΄νΈλ₯Ό μ 곡ν©λλ€:\n\n"
|
| 224 |
+
analysis_result += "1. λ°μ΄ν° κΈ°λ° λΆμ (κΈ°λ³Έμ μΈ μμ½)\n"
|
| 225 |
+
analysis_result += "2. μ£Όμ κ°κ²© λ° μμ λν₯\n"
|
| 226 |
+
analysis_result += "3. μμ°λ λ° λ¬΄μ ν¨ν΄\n\n"
|
| 227 |
+
|
| 228 |
+
analysis_result += "μ΄ λΆμμ UN κΈλ‘λ² μλ λ° λμ
ν΅κ³ λ°μ΄ν°μ
μ κΈ°λ°μΌλ‘ ν©λλ€.\n\n"
|
| 229 |
+
|
| 230 |
+
return analysis_result
|
| 231 |
|
| 232 |
# ββββββββββββββββββββββββββββββββ System Prompt βββββββββββββββββββββββββ
|
| 233 |
+
def get_system_prompt(mode="price_forecast", style="professional", include_search_results=True, include_uploaded_files=False) -> str:
|
| 234 |
"""
|
| 235 |
+
Generate a system prompt for the 'Agricultural Price & Demand Forecast AI Assistant' interface based on:
|
| 236 |
+
- The selected analysis mode and style
|
| 237 |
+
- Guidelines for using agricultural datasets, web search results and uploaded files
|
| 238 |
"""
|
| 239 |
+
base_prompt = """
|
| 240 |
+
λΉμ μ λμ
λ°μ΄ν° μ λ¬Έκ°λ‘μ λμ°λ¬Ό κ°κ²© μμΈ‘κ³Ό μμ λΆμμ μννλ AI μ΄μμ€ν΄νΈμ
λλ€.
|
| 241 |
+
|
| 242 |
+
μ£Όμ μ무:
|
| 243 |
+
1. UN κΈλ‘λ² μλ λ° λμ
ν΅κ³ λ°μ΄ν°μ
μ κΈ°λ°μΌλ‘ λμ°λ¬Ό μμ₯ λΆμ
|
| 244 |
+
2. λμ°λ¬Ό κ°κ²© μΆμΈ μμΈ‘ λ° μμ ν¨ν΄ λΆμ
|
| 245 |
+
3. λ°μ΄ν°λ₯Ό λ°νμΌλ‘ λͺ
ννκ³ κ·Όκ±° μλ λΆμ μ 곡
|
| 246 |
+
4. κ΄λ ¨ μ 보μ μΈμ¬μ΄νΈλ₯Ό 체κ³μ μΌλ‘ ꡬμ±νμ¬ μ μ
|
| 247 |
+
5. μκ°μ μ΄ν΄λ₯Ό λκΈ° μν΄ μ°¨νΈ, κ·Έλν λ±μ μ μ ν νμ©
|
| 248 |
+
|
| 249 |
+
μ€μ κ°μ΄λλΌμΈ:
|
| 250 |
+
- λ°μ΄ν°μ κΈ°λ°ν κ°κ΄μ λΆμμ μ 곡νμΈμ
|
| 251 |
+
- λΆμ κ³Όμ κ³Ό λ°©λ²λ‘ μ λͺ
νν μ€λͺ
νμΈμ
|
| 252 |
+
- ν΅κ³μ μ λ’°μ±κ³Ό νκ³μ μ ν¬λͺ
νκ² μ μνμΈμ
|
| 253 |
+
- μ΄ν΄νκΈ° μ¬μ΄ μκ°μ μμλ‘ λΆμ κ²°κ³Όλ₯Ό 보μνμΈμ
|
| 254 |
+
- λ§ν¬λ€μ΄μ νμ©ν΄ μλ΅μ 체κ³μ μΌλ‘ ꡬμ±νμΈμ
|
|
|
|
| 255 |
"""
|
| 256 |
|
| 257 |
mode_prompts = {
|
| 258 |
+
"price_forecast": """
|
| 259 |
+
λμ°λ¬Ό κ°κ²© μμΈ‘ λ° μμ₯ λΆμμ μ§μ€ν©λλ€:
|
| 260 |
+
- κ³Όκ±° κ°κ²© λ°μ΄ν° ν¨ν΄μ κΈ°λ°ν μμΈ‘ μ 곡
|
| 261 |
+
- κ°κ²© λ³λμ± μμΈ λΆμ(κ³μ μ±, λ μ¨, μ μ±
λ±)
|
| 262 |
+
- λ¨κΈ° λ° μ€μ₯κΈ° κ°κ²© μ λ§ μ μ
|
| 263 |
+
- κ°κ²©μ μν₯μ λ―ΈμΉλ κ΅λ΄μΈ μμΈ μλ³
|
| 264 |
+
- μμ₯ λΆνμ€μ±κ³Ό 리μ€ν¬ μμ κ°μ‘°
|
| 265 |
+
""",
|
| 266 |
+
"market_trend": """
|
| 267 |
+
μμ₯ λν₯ λ° μμ ν¨ν΄ λΆμμ μ§μ€ν©λλ€:
|
| 268 |
+
- μ£Όμ λμ°λ¬Ό μμ λ³ν ν¨ν΄ μλ³
|
| 269 |
+
- μλΉμ μ νΈλ λ° κ΅¬λ§€ νλ λΆμ
|
| 270 |
+
- μμ₯ μΈκ·Έλ¨ΌνΈ λ° νμμμ₯ κΈ°ν νμ
|
| 271 |
+
- μμ₯ νλ/μΆμ νΈλ λ νκ°
|
| 272 |
+
- μμ νλ ₯μ± λ° κ°κ²© λ―Όκ°λ λΆμ
|
| 273 |
""",
|
| 274 |
+
"production_analysis": """
|
| 275 |
+
μμ°λ λΆμ λ° μλ μ보 μ λ§μ μ§μ€ν©λλ€:
|
| 276 |
+
- μλ¬Ό μμ°λ μΆμΈ λ° λ³λ μμΈ λΆμ
|
| 277 |
+
- μλ μμ°κ³Ό μΈκ΅¬ μ±μ₯ κ°μ κ΄κ³ νκ°
|
| 278 |
+
- κ΅κ°/μ§μλ³ μμ° μλ λΉκ΅
|
| 279 |
+
- μλ μ보 μν μμ λ° μ·¨μ½μ μλ³
|
| 280 |
+
- μμ°μ± ν₯μ μ λ΅ λ° κΈ°ν μ μ
|
| 281 |
""",
|
| 282 |
+
"agricultural_policy": """
|
| 283 |
+
λμ
μ μ±
λ° κ·μ μν₯ λΆμμ μ§μ€ν©λλ€:
|
| 284 |
+
- μ λΆ μ μ±
κ³Ό, 보쑰κΈ, κ·μ μ μμ₯ μν₯ λΆμ
|
| 285 |
+
- κ΅μ 무μ μ μ±
κ³Ό κ΄μΈμ λμ°λ¬Ό κ°κ²© μν₯ νκ°
|
| 286 |
+
- λμ
μ§μ νλ‘κ·Έλ¨μ ν¨κ³Όμ± κ²ν
|
| 287 |
+
- κ·μ νκ²½ λ³νμ λ°λ₯Έ μμ₯ μ‘°μ μμΈ‘
|
| 288 |
+
- μ μ±
μ κ°μ
μ μλλ/μλμΉ μμ κ²°κ³Ό λΆμ
|
| 289 |
""",
|
| 290 |
+
"climate_impact": """
|
| 291 |
+
κΈ°ν λ³νκ° λμ
μ λ―ΈμΉλ μν₯ λΆμμ μ§μ€ν©λλ€:
|
| 292 |
+
- κΈ°ν λ³νμ λμ°λ¬Ό μμ°λ/νμ§ κ°μ μκ΄κ΄κ³ λΆμ
|
| 293 |
+
- κΈ°μ μ΄λ³μ΄ κ°κ²© λ³λμ±μ λ―ΈμΉλ μν₯ νκ°
|
| 294 |
+
- μ₯κΈ°μ κΈ°ν μΆμΈμ λ°λ₯Έ λμ
ν¨ν΄ λ³ν μμΈ‘
|
| 295 |
+
- κΈ°ν ν볡λ ₯ μλ λμ
μμ€ν
μ λ΅ μ μ
|
| 296 |
+
- μ§μλ³ κΈ°ν μν λ
ΈμΆλ λ° μ·¨μ½μ± λ§€ν
|
| 297 |
"""
|
| 298 |
}
|
| 299 |
|
| 300 |
style_guides = {
|
| 301 |
+
"professional": "μ λ¬Έμ μ΄κ³ νμ μ μΈ μ΄μ‘°λ₯Ό μ¬μ©νμΈμ. κΈ°μ μ μ©μ΄λ₯Ό μ μ ν μ¬μ©νκ³ μ²΄κ³μ μΈ λ°μ΄ν° λΆμμ μ 곡νμΈμ.",
|
| 302 |
+
"simple": "μ½κ³ κ°κ²°ν μΈμ΄λ‘ μ€λͺ
νμΈμ. μ λ¬Έ μ©μ΄λ μ΅μννκ³ ν΅μ¬ κ°λ
μ μΌμμ μΈ ννμΌλ‘ μ λ¬νμΈμ.",
|
| 303 |
+
"detailed": "μμΈνκ³ ν¬κ΄μ μΈ λΆμμ μ 곡νμΈμ. λ€μν λ°μ΄ν° ν¬μΈνΈ, ν΅κ³μ λμμ€, κ·Έλ¦¬κ³ μ¬λ¬ μλ리μ€λ₯Ό κ³ λ €ν μ¬μΈ΅ λΆμμ μ μνμΈμ.",
|
| 304 |
+
"action_oriented": "μ€ν κ°λ₯ν μΈμ¬μ΄νΈμ ꡬ체μ μΈ κΆμ₯μ¬νμ μ΄μ μ λ§μΆμΈμ. 'λ€μ λ¨κ³' λ° 'μ€μ§μ μ‘°μΈ' μΉμ
μ ν¬ν¨νμΈμ."
|
| 305 |
}
|
| 306 |
|
| 307 |
+
dataset_guide = """
|
| 308 |
+
UN κΈλ‘λ² μλ λ° λμ
ν΅κ³ λ°μ΄ν°μ
νμ© μ§μΉ¨:
|
| 309 |
+
- μ 곡λ λ°μ΄ν°μ
λΆμ κ²°κ³Όλ₯Ό μλ΅μ μ£Όμ κ·Όκ±°λ‘ μ¬μ©νμΈμ
|
| 310 |
+
- λ°μ΄ν°μ μΆμ²μ μ°λλ₯Ό λͺ
νν μΈμ©νμΈμ
|
| 311 |
+
- λ°μ΄ν°μ
λ΄ μ£Όμ λ³μ κ°μ κ΄κ³λ₯Ό λΆμνμ¬ μΈμ¬μ΄νΈλ₯Ό λμΆνμΈμ
|
| 312 |
+
- λ°μ΄ν°μ νκ³μ λΆνμ€μ±μ ν¬λͺ
νκ² μΈκΈνμΈμ
|
| 313 |
+
- νμμ λ°μ΄ν° 격차λ₯Ό μλ³νκ³ μΆκ° μ°κ΅¬κ° νμν μμμ μ μνμΈμ
|
| 314 |
+
"""
|
| 315 |
+
|
| 316 |
search_guide = """
|
| 317 |
+
μΉ κ²μ κ²°κ³Ό νμ© μ§μΉ¨:
|
| 318 |
+
- λ°μ΄ν°μ
λΆμμ 보μνλ μ΅μ μμ₯ μ λ³΄λ‘ κ²μ κ²°κ³Όλ₯Ό νμ©νμΈμ
|
| 319 |
+
- κ° μ 보μ μΆμ²λ₯Ό λ§ν¬λ€μ΄ λ§ν¬λ‘ ν¬ν¨νμΈμ: [μΆμ²λͺ
](URL)
|
| 320 |
+
- μ£Όμ μ£Όμ₯μ΄λ λ°μ΄ν° ν¬μΈνΈλ§λ€ μΆμ²λ₯Ό νμνμΈμ
|
| 321 |
+
- μΆμ²κ° μμΆ©ν κ²½μ°, λ€μν κ΄μ κ³Ό μ λ’°λλ₯Ό μ€λͺ
νμΈμ
|
| 322 |
+
- κ΄λ ¨ λμμ λ§ν¬λ [λΉλμ€: μ λͺ©](video_url) νμμΌλ‘ ν¬ν¨νμΈμ
|
| 323 |
+
- κ²μ μ 보λ₯Ό μΌκ΄λκ³ μ²΄κ³μ μΈ μλ΅μΌλ‘ ν΅ν©νμΈμ
|
| 324 |
+
- λͺ¨λ μ£Όμ μΆμ²λ₯Ό λμ΄ν "μ°Έκ³ μλ£" μΉμ
μ λ§μ§λ§μ ν¬ν¨νμΈμ
|
| 325 |
"""
|
| 326 |
|
| 327 |
upload_guide = """
|
| 328 |
+
μ
λ‘λλ νμΌ νμ© μ§μΉ¨:
|
| 329 |
+
- μ
λ‘λλ νμΌμ μλ΅μ μ£Όμ μ 보μμΌλ‘ νμ©νμΈμ
|
| 330 |
+
- 쿼리μ μ§μ κ΄λ ¨λ νμΌ μ 보λ₯Ό μΆμΆνκ³ κ°μ‘°νμΈμ
|
| 331 |
+
- κ΄λ ¨ ꡬμ μ μΈμ©νκ³ νΉμ νμΌμ μΆμ²λ‘ οΏ½οΏ½οΏ½μ©νμΈμ
|
| 332 |
+
- CSV νμΌμ μμΉ λ°μ΄ν°λ μμ½ λ¬Έμ₯μΌλ‘ λ³ννμΈμ
|
| 333 |
+
- PDF μ½ν
μΈ λ νΉμ μΉμ
μ΄λ νμ΄μ§λ₯Ό μ°Έμ‘°νμΈμ
|
| 334 |
+
- νμΌ μ 보λ₯Ό μΉ κ²μ κ²°κ³Όμ μννκ² ν΅ν©νμΈμ
|
| 335 |
+
- μ λ³΄κ° μμΆ©ν κ²½μ°, μΌλ°μ μΈ μΉ κ²°κ³Όλ³΄λ€ νμΌ μ½ν
μΈ λ₯Ό μ°μ μνμΈμ
|
| 336 |
"""
|
| 337 |
|
| 338 |
# Base prompt
|
| 339 |
+
final_prompt = base_prompt
|
| 340 |
+
|
| 341 |
+
# Add mode-specific guidance
|
| 342 |
+
if mode in mode_prompts:
|
| 343 |
+
final_prompt += "\n" + mode_prompts[mode]
|
| 344 |
|
| 345 |
# Style
|
| 346 |
if style in style_guides:
|
| 347 |
+
final_prompt += f"\n\nλΆμ μ€νμΌ: {style_guides[style]}"
|
| 348 |
+
|
| 349 |
+
# Always include dataset guide
|
| 350 |
+
final_prompt += f"\n\n{dataset_guide}"
|
| 351 |
|
| 352 |
if include_search_results:
|
| 353 |
final_prompt += f"\n\n{search_guide}"
|
|
|
|
| 356 |
final_prompt += f"\n\n{upload_guide}"
|
| 357 |
|
| 358 |
final_prompt += """
|
| 359 |
+
\n\nμλ΅ νμ μꡬμ¬ν:
|
| 360 |
+
- λ§ν¬λ€μ΄ μ λͺ©(## λ° ###)μ μ¬μ©νμ¬ μλ΅μ 체κ³μ μΌλ‘ ꡬμ±νμΈμ
|
| 361 |
+
- μ€μν μ μ κ΅΅μ ν
μ€νΈ(**ν
μ€νΈ**)λ‘ κ°μ‘°νμΈμ
|
| 362 |
+
- 3-5κ°μ νμ μ§λ¬Έμ ν¬ν¨ν "κ΄λ ¨ μ§λ¬Έ" μΉμ
μ λ§μ§λ§μ μΆκ°νμΈμ
|
| 363 |
+
- μ μ ν κ°κ²©κ³Ό λ¨λ½ ꡬλΆμΌλ‘ μλ΅μ μμννμΈμ
|
| 364 |
+
- λͺ¨λ λ§ν¬λ λ§ν¬λ€μ΄ νμμΌλ‘ ν΄λ¦ κ°λ₯νκ² λ§λμΈμ: [ν
μ€νΈ](url)
|
| 365 |
+
- κ°λ₯ν κ²½μ° λ°μ΄ν°λ₯Ό μκ°μ μΌλ‘ νν(ν, κ·Έλν λ±μ μ€λͺ
)νμΈμ
|
| 366 |
"""
|
| 367 |
return final_prompt
|
| 368 |
|
| 369 |
# ββββββββββββββββββββββββββββββββ Brave Search API ββββββββββββββββββββββββ
|
| 370 |
@st.cache_data(ttl=3600)
|
| 371 |
+
def brave_search(query: str, count: int = 10):
|
| 372 |
if not BRAVE_KEY:
|
| 373 |
raise RuntimeError("β οΈ SERPHOUSE_API_KEY (Brave API Key) environment variable is empty.")
|
| 374 |
|
| 375 |
headers = {"Accept": "application/json", "Accept-Encoding": "gzip", "X-Subscription-Token": BRAVE_KEY}
|
| 376 |
+
params = {"q": query + " λμ°λ¬Ό κ°κ²© λν₯ λμ
λ°μ΄ν°", "count": str(count)}
|
| 377 |
|
| 378 |
for attempt in range(3):
|
| 379 |
try:
|
|
|
|
| 411 |
return []
|
| 412 |
|
| 413 |
@st.cache_data(ttl=3600)
|
| 414 |
+
def brave_video_search(query: str, count: int = 3):
|
| 415 |
if not BRAVE_KEY:
|
| 416 |
raise RuntimeError("β οΈ SERPHOUSE_API_KEY (Brave API Key) environment variable is empty.")
|
| 417 |
|
| 418 |
headers = {"Accept": "application/json","Accept-Encoding": "gzip","X-Subscription-Token": BRAVE_KEY}
|
| 419 |
+
params = {"q": query + " λμ°λ¬Ό κ°κ²© λμ
μμ₯", "count": str(count)}
|
| 420 |
|
| 421 |
for attempt in range(3):
|
| 422 |
try:
|
|
|
|
| 445 |
return []
|
| 446 |
|
| 447 |
@st.cache_data(ttl=3600)
|
| 448 |
+
def brave_news_search(query: str, count: int = 3):
|
| 449 |
if not BRAVE_KEY:
|
| 450 |
raise RuntimeError("β οΈ SERPHOUSE_API_KEY (Brave API Key) environment variable is empty.")
|
| 451 |
|
| 452 |
headers = {"Accept": "application/json","Accept-Encoding": "gzip","X-Subscription-Token": BRAVE_KEY}
|
| 453 |
+
params = {"q": query + " λμ°λ¬Ό κ°κ²© λν₯ λμ
", "count": str(count)}
|
| 454 |
|
| 455 |
for attempt in range(3):
|
| 456 |
try:
|
|
|
|
| 481 |
|
| 482 |
def mock_results(query: str) -> str:
|
| 483 |
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 484 |
+
return (f"# λ체 κ²μ μ½ν
μΈ (μμ± μκ°: {ts})\n\n"
|
| 485 |
+
f"'{query}'μ λν κ²μ API μμ²μ΄ μ€ν¨νκ±°λ κ²°κ³Όκ° μμ΅λλ€. "
|
| 486 |
+
f"κΈ°μ‘΄ μ§μμ κΈ°λ°μΌλ‘ μλ΅μ μμ±ν΄οΏ½οΏ½μΈμ.\n\n"
|
| 487 |
+
f"λ€μ μ¬νμ κ³ λ €νμΈμ:\n\n"
|
| 488 |
+
f"- {query}μ κ΄ν κΈ°λ³Έ κ°λ
κ³Ό μ€μμ±\n"
|
| 489 |
+
f"- μΌλ°μ μΌλ‘ μλ €μ§ κ΄λ ¨ ν΅κ³λ μΆμΈ\n"
|
| 490 |
+
f"- μ΄ μ£Όμ μ λν μ λ¬Έκ° μ견\n"
|
| 491 |
+
f"- λ
μκ° κ°μ§ μ μλ μ§λ¬Έ\n\n"
|
| 492 |
+
f"μ°Έκ³ : μ΄λ μ€μκ° λ°μ΄ν°κ° μλ λ체 μ§μΉ¨μ
λλ€.\n\n")
|
| 493 |
|
| 494 |
def do_web_search(query: str) -> str:
|
| 495 |
try:
|
| 496 |
+
arts = brave_search(query, 10)
|
| 497 |
if not arts:
|
| 498 |
logging.warning("No search results, using fallback content")
|
| 499 |
return mock_results(query)
|
|
|
|
| 501 |
videos = brave_video_search(query, 2)
|
| 502 |
news = brave_news_search(query, 3)
|
| 503 |
|
| 504 |
+
result = "# μΉ κ²μ κ²°κ³Ό\nλ€μ κ²°κ³Όλ₯Ό νμ©νμ¬ λ°μ΄ν°μ
λΆμμ 보μνλ ν¬κ΄μ μΈ λ΅λ³μ μ 곡νμΈμ.\n\n"
|
| 505 |
|
| 506 |
+
result += "## μΉ κ²°κ³Ό\n\n"
|
| 507 |
+
for a in arts[:5]:
|
| 508 |
+
result += f"### κ²°κ³Ό {a['index']}: {a['title']}\n\n{a['snippet']}\n\n"
|
| 509 |
+
result += f"**μΆμ²**: [{a['displayed_link']}]({a['link']})\n\n---\n"
|
| 510 |
|
| 511 |
+
if news:
|
| 512 |
+
result += "## λ΄μ€ κ²°κ³Ό\n\n"
|
| 513 |
+
for n in news:
|
| 514 |
+
result += f"### {n['title']}\n\n{n['description']}\n\n"
|
| 515 |
+
result += f"**μΆμ²**: [{n['source']}]({n['url']}) - {n['date']}\n\n---\n"
|
| 516 |
+
|
| 517 |
if videos:
|
| 518 |
+
result += "## λΉλμ€ κ²°κ³Ό\n\n"
|
| 519 |
for vid in videos:
|
| 520 |
result += f"### {vid['title']}\n\n"
|
| 521 |
if vid.get('thumbnail_url'):
|
| 522 |
+
result += f"\n\n"
|
| 523 |
+
result += f"**μμ²**: [{vid['source']}]({vid['video_url']})\n\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 524 |
|
| 525 |
return result
|
| 526 |
|
|
|
|
| 538 |
if len(text) > 10000:
|
| 539 |
text = text[:9700] + "...(truncated)..."
|
| 540 |
|
| 541 |
+
result = f"## ν
μ€νΈ νμΌ: {file.name}\n\n" + text
|
| 542 |
return result
|
| 543 |
except Exception as e:
|
| 544 |
logging.error(f"Error processing text file: {str(e)}")
|
| 545 |
+
return f"ν
μ€νΈ νμΌ μ²λ¦¬ μ€λ₯: {str(e)}"
|
| 546 |
|
| 547 |
def process_csv_file(file):
|
| 548 |
try:
|
|
|
|
| 550 |
file.seek(0)
|
| 551 |
|
| 552 |
df = pd.read_csv(io.BytesIO(content))
|
| 553 |
+
result = f"## CSV νμΌ: {file.name}\n\n"
|
| 554 |
+
result += f"- ν: {len(df)}\n"
|
| 555 |
+
result += f"- μ΄: {len(df.columns)}\n"
|
| 556 |
+
result += f"- μ΄ μ΄λ¦: {', '.join(df.columns.tolist())}\n\n"
|
| 557 |
|
| 558 |
+
result += "### λ°μ΄ν° 미리보기\n\n"
|
| 559 |
preview_df = df.head(10)
|
| 560 |
try:
|
| 561 |
markdown_table = preview_df.to_markdown(index=False)
|
| 562 |
if markdown_table:
|
| 563 |
result += markdown_table + "\n\n"
|
| 564 |
else:
|
| 565 |
+
result += "CSV λ°μ΄ν°λ₯Ό νμν μ μμ΅λλ€.\n\n"
|
| 566 |
except Exception as e:
|
| 567 |
logging.error(f"Markdown table conversion error: {e}")
|
| 568 |
+
result += "ν
μ€νΈλ‘ λ°μ΄ν° νμ:\n\n" + str(preview_df) + "\n\n"
|
| 569 |
|
| 570 |
num_cols = df.select_dtypes(include=['number']).columns
|
| 571 |
if len(num_cols) > 0:
|
| 572 |
+
result += "### κΈ°λ³Έ ν΅κ³ μ 보\n\n"
|
| 573 |
try:
|
| 574 |
stats_df = df[num_cols].describe().round(2)
|
| 575 |
stats_markdown = stats_df.to_markdown()
|
| 576 |
if stats_markdown:
|
| 577 |
result += stats_markdown + "\n\n"
|
| 578 |
else:
|
| 579 |
+
result += "ν΅κ³ μ 보λ₯Ό νμν μ μμ΅λλ€.\n\n"
|
| 580 |
except Exception as e:
|
| 581 |
logging.error(f"Statistical info conversion error: {e}")
|
| 582 |
+
result += "ν΅κ³ μ 보λ₯Ό μμ±ν μ μμ΅λλ€.\n\n"
|
| 583 |
|
| 584 |
return result
|
| 585 |
except Exception as e:
|
| 586 |
logging.error(f"CSV file processing error: {str(e)}")
|
| 587 |
+
return f"CSV νμΌ μ²λ¦¬ μ€λ₯: {str(e)}"
|
| 588 |
|
| 589 |
def process_pdf_file(file):
|
| 590 |
try:
|
|
|
|
| 594 |
pdf_file = io.BytesIO(file_bytes)
|
| 595 |
reader = PyPDF2.PdfReader(pdf_file, strict=False)
|
| 596 |
|
| 597 |
+
result = f"## PDF νμΌ: {file.name}\n\n- μ΄ νμ΄μ§: {len(reader.pages)}\n\n"
|
| 598 |
|
| 599 |
max_pages = min(5, len(reader.pages))
|
| 600 |
all_text = ""
|
|
|
|
| 603 |
try:
|
| 604 |
page = reader.pages[i]
|
| 605 |
page_text = page.extract_text()
|
| 606 |
+
current_page_text = f"### νμ΄μ§ {i+1}\n\n"
|
| 607 |
if page_text and len(page_text.strip()) > 0:
|
| 608 |
if len(page_text) > 1500:
|
| 609 |
+
current_page_text += page_text[:1500] + "...(μΆμ½λ¨)...\n\n"
|
| 610 |
else:
|
| 611 |
current_page_text += page_text + "\n\n"
|
| 612 |
else:
|
| 613 |
+
current_page_text += "(ν
μ€νΈλ₯Ό μΆμΆν μ μμ)\n\n"
|
| 614 |
|
| 615 |
all_text += current_page_text
|
| 616 |
|
| 617 |
if len(all_text) > 8000:
|
| 618 |
+
all_text += "...(λλ¨Έμ§ νμ΄μ§ μΆμ½λ¨)...\n\n"
|
| 619 |
break
|
| 620 |
|
| 621 |
except Exception as page_err:
|
| 622 |
logging.error(f"Error processing PDF page {i+1}: {str(page_err)}")
|
| 623 |
+
all_text += f"### νμ΄μ§ {i+1}\n\n(λ΄μ© μΆμΆ μ€λ₯: {str(page_err)})\n\n"
|
| 624 |
|
| 625 |
if len(reader.pages) > max_pages:
|
| 626 |
+
all_text += f"\nμ°Έκ³ : μ²μ {max_pages} νμ΄μ§λ§ νμλ©λλ€.\n\n"
|
| 627 |
|
| 628 |
+
result += "### PDF λ΄μ©\n\n" + all_text
|
| 629 |
return result
|
| 630 |
|
| 631 |
except Exception as e:
|
| 632 |
logging.error(f"PDF file processing error: {str(e)}")
|
| 633 |
+
return f"## PDF νμΌ: {file.name}\n\nμ€λ₯: {str(e)}\n\nμ²λ¦¬ν μ μμ΅λλ€."
|
| 634 |
|
| 635 |
def process_uploaded_files(files):
|
| 636 |
if not files:
|
| 637 |
return None
|
| 638 |
|
| 639 |
+
result = "# μ
λ‘λλ νμΌ λ΄μ©\n\nμ¬μ©μκ° μ 곡ν νμΌμ λ΄μ©μ
λλ€.\n\n"
|
| 640 |
for file in files:
|
| 641 |
try:
|
| 642 |
ext = file.name.split('.')[-1].lower()
|
|
|
|
| 647 |
elif ext == 'pdf':
|
| 648 |
result += process_pdf_file(file) + "\n\n---\n\n"
|
| 649 |
else:
|
| 650 |
+
result += f"### μ§μλμ§ μλ νμΌ: {file.name}\n\n---\n\n"
|
| 651 |
except Exception as e:
|
| 652 |
logging.error(f"File processing error {file.name}: {e}")
|
| 653 |
+
result += f"### νμΌ μ²λ¦¬ μ€λ₯: {file.name}\n\nμ€λ₯: {e}\n\n---\n\n"
|
| 654 |
|
| 655 |
return result
|
| 656 |
|
|
|
|
| 678 |
response = client.chat.completions.create(
|
| 679 |
model="gpt-4.1-mini",
|
| 680 |
messages=[
|
| 681 |
+
{"role": "system", "content": "λμ
λ° λμ°λ¬Όμ κ΄ν μ΄λ―Έμ§ ν둬ννΈλ₯Ό μμ±ν©λλ€. ν μ€μ μμ΄λ‘ λ ν둬ννΈλ§ λ°ννμΈμ, λ€λ₯Έ ν
μ€νΈλ ν¬ν¨νμ§ λ§μΈμ."},
|
| 682 |
+
{"role": "user", "content": f"μ£Όμ : {topic}\n\n---\n{response_text}\n\n---"}
|
| 683 |
],
|
| 684 |
temperature=1,
|
| 685 |
max_tokens=80,
|
|
|
|
| 688 |
return response.choices[0].message.content.strip()
|
| 689 |
except Exception as e:
|
| 690 |
logging.error(f"OpenAI image prompt generation error: {e}")
|
| 691 |
+
return f"A professional photograph of agricultural produce and farm fields, data visualization of crop prices and trends, high quality"
|
| 692 |
|
| 693 |
+
def md_to_html(md: str, title="λμ°λ¬Ό μμ μμΈ‘ λΆμ κ²°κ³Ό"):
|
| 694 |
return f"<!DOCTYPE html><html><head><title>{title}</title><meta charset='utf-8'></head><body>{markdown.markdown(md)}</body></html>"
|
| 695 |
|
| 696 |
def keywords(text: str, top=5):
|
|
|
|
| 698 |
return " ".join(cleaned.split()[:top])
|
| 699 |
|
| 700 |
# ββββββββββββββββββββββββββββββββ Streamlit UI ββββββββββββββββββββββββββββ
|
| 701 |
+
def agricultural_price_forecast_app():
|
| 702 |
+
st.title("λμ°λ¬Ό μμ λ° κ°κ²© μμΈ‘ AI μ΄μμ€ν΄νΈ")
|
| 703 |
+
st.markdown("UN κΈλ‘λ² μλ λ° λμ
ν΅κ³ λ°μ΄ν°μ
λΆμ κΈ°λ°μ λμ°λ¬Ό μμ₯ μμΈ‘")
|
| 704 |
|
| 705 |
if "ai_model" not in st.session_state:
|
| 706 |
st.session_state.ai_model = "gpt-4.1-mini"
|
|
|
|
| 712 |
st.session_state.generate_image = False
|
| 713 |
if "web_search_enabled" not in st.session_state:
|
| 714 |
st.session_state.web_search_enabled = True
|
| 715 |
+
if "analysis_mode" not in st.session_state:
|
| 716 |
+
st.session_state.analysis_mode = "price_forecast"
|
| 717 |
if "response_style" not in st.session_state:
|
| 718 |
st.session_state.response_style = "professional"
|
| 719 |
|
| 720 |
sb = st.sidebar
|
| 721 |
+
sb.title("λΆμ μ€μ ")
|
| 722 |
|
| 723 |
+
# Kaggle dataset info display
|
| 724 |
+
if sb.checkbox("λ°μ΄ν°μ
μ 보 νμ", value=False):
|
| 725 |
+
st.info("UN κΈλ‘λ² μλ λ° λμ
ν΅κ³ λ°μ΄ν°μ
μ λΆλ¬μ€λ μ€...")
|
| 726 |
+
dataset_info = load_agriculture_dataset()
|
| 727 |
+
if dataset_info:
|
| 728 |
+
st.success(f"λ°μ΄ν°μ
λ‘λ μλ£: {len(dataset_info['files'])}κ° νμΌ")
|
| 729 |
+
|
| 730 |
+
with st.expander("λ°μ΄ν°μ
미리보기", expanded=False):
|
| 731 |
+
for file_info in dataset_info['files'][:5]:
|
| 732 |
+
st.write(f"**{file_info['name']}** ({file_info['size_mb']} MB)")
|
| 733 |
+
else:
|
| 734 |
+
st.error("λ°μ΄ν°μ
μ λΆλ¬μ€λλ° μ€ν¨νμ΅λλ€. Kaggle API μ€μ μ νμΈνμΈμ.")
|
| 735 |
+
|
| 736 |
+
sb.subheader("λΆμ ꡬμ±")
|
| 737 |
sb.selectbox(
|
| 738 |
+
"λΆμ λͺ¨λ",
|
| 739 |
+
options=list(ANALYSIS_MODES.keys()),
|
| 740 |
+
format_func=lambda x: ANALYSIS_MODES[x],
|
| 741 |
+
key="analysis_mode"
|
| 742 |
)
|
| 743 |
|
| 744 |
sb.selectbox(
|
| 745 |
+
"μλ΅ μ€νμΌ",
|
| 746 |
options=list(RESPONSE_STYLES.keys()),
|
| 747 |
format_func=lambda x: RESPONSE_STYLES[x],
|
| 748 |
key="response_style"
|
| 749 |
)
|
| 750 |
|
| 751 |
# Example queries
|
| 752 |
+
sb.subheader("μμ μ§λ¬Έ")
|
| 753 |
c1, c2, c3 = sb.columns(3)
|
| 754 |
+
if c1.button("μ κ°κ²© μ λ§", key="ex1"):
|
| 755 |
process_example(EXAMPLE_QUERIES["example1"])
|
| 756 |
+
if c2.button("κΈ°ν μν₯", key="ex2"):
|
| 757 |
process_example(EXAMPLE_QUERIES["example2"])
|
| 758 |
+
if c3.button("곑물 μμ₯", key="ex3"):
|
| 759 |
process_example(EXAMPLE_QUERIES["example3"])
|
| 760 |
|
| 761 |
+
sb.subheader("κΈ°ν μ€μ ")
|
| 762 |
+
sb.toggle("μλ μ μ₯", key="auto_save")
|
| 763 |
+
sb.toggle("μ΄λ―Έμ§ μλ μμ±", key="generate_image")
|
| 764 |
|
| 765 |
+
web_search_enabled = sb.toggle("μΉ κ²μ μ¬μ©", value=st.session_state.web_search_enabled)
|
| 766 |
st.session_state.web_search_enabled = web_search_enabled
|
| 767 |
|
| 768 |
if web_search_enabled:
|
| 769 |
+
st.sidebar.info("β
μΉ κ²μ κ²°κ³Όκ° μλ΅μ ν΅ν©λ©λλ€.")
|
| 770 |
|
| 771 |
# Download the latest response
|
| 772 |
latest_response = next(
|
|
|
|
| 782 |
first_line = latest_response.split('\n', 1)[0].strip()
|
| 783 |
title = first_line[:40] + "..." if len(first_line) > 40 else first_line
|
| 784 |
|
| 785 |
+
sb.subheader("μ΅μ μλ΅ λ€μ΄λ‘λ")
|
| 786 |
d1, d2 = sb.columns(2)
|
| 787 |
+
d1.download_button("λ§ν¬λ€μ΄μΌλ‘ λ€μ΄λ‘λ", latest_response,
|
| 788 |
file_name=f"{title}.md", mime="text/markdown")
|
| 789 |
+
d2.download_button("HTMLλ‘ λ€μ΄λ‘λ", md_to_html(latest_response, title),
|
| 790 |
file_name=f"{title}.html", mime="text/html")
|
| 791 |
|
| 792 |
# JSON conversation record upload
|
| 793 |
+
up = sb.file_uploader("λν κΈ°λ‘ λΆλ¬μ€κΈ° (.json)", type=["json"], key="json_uploader")
|
| 794 |
if up:
|
| 795 |
try:
|
| 796 |
st.session_state.messages = json.load(up)
|
| 797 |
+
sb.success("λν κΈ°λ‘μ μ±κ³΅μ μΌλ‘ λΆλ¬μμ΅λλ€")
|
| 798 |
except Exception as e:
|
| 799 |
+
sb.error(f"λΆλ¬μ€κΈ° μ€ν¨: {e}")
|
| 800 |
|
| 801 |
# JSON conversation record download
|
| 802 |
+
if sb.button("λν κΈ°λ‘μ JSONμΌλ‘ λ€μ΄λ‘λ"):
|
| 803 |
sb.download_button(
|
| 804 |
+
"μ μ₯",
|
| 805 |
data=json.dumps(st.session_state.messages, ensure_ascii=False, indent=2),
|
| 806 |
file_name="conversation_history.json",
|
| 807 |
mime="application/json"
|
| 808 |
)
|
| 809 |
|
| 810 |
# File Upload
|
| 811 |
+
st.subheader("νμΌ μ
λ‘λ")
|
| 812 |
uploaded_files = st.file_uploader(
|
| 813 |
+
"μ°Έκ³ μλ£λ‘ μ¬μ©ν νμΌ μ
λ‘λ (txt, csv, pdf)",
|
| 814 |
type=["txt", "csv", "pdf"],
|
| 815 |
accept_multiple_files=True,
|
| 816 |
key="file_uploader"
|
|
|
|
| 818 |
|
| 819 |
if uploaded_files:
|
| 820 |
file_count = len(uploaded_files)
|
| 821 |
+
st.success(f"{file_count}κ° νμΌμ΄ μ
λ‘λλμμ΅λλ€. μ§μμ λν μμ€λ‘ μ¬μ©λ©λλ€.")
|
| 822 |
|
| 823 |
+
with st.expander("μ
λ‘λλ νμΌ λ―Έλ¦¬λ³΄κΈ°", expanded=False):
|
| 824 |
for idx, file in enumerate(uploaded_files):
|
| 825 |
+
st.write(f"**νμΌλͺ
:** {file.name}")
|
| 826 |
ext = file.name.split('.')[-1].lower()
|
| 827 |
|
| 828 |
if ext == 'txt':
|
| 829 |
preview = file.read(1000).decode('utf-8', errors='ignore')
|
| 830 |
file.seek(0)
|
| 831 |
st.text_area(
|
| 832 |
+
f"{file.name} 미리보기",
|
| 833 |
preview + ("..." if len(preview) >= 1000 else ""),
|
| 834 |
height=150
|
| 835 |
)
|
|
|
|
| 837 |
try:
|
| 838 |
df = pd.read_csv(file)
|
| 839 |
file.seek(0)
|
| 840 |
+
st.write("CSV 미리보기 (μ΅λ 5ν)")
|
| 841 |
st.dataframe(df.head(5))
|
| 842 |
except Exception as e:
|
| 843 |
+
st.error(f"CSV 미리보기 μ€ν¨: {e}")
|
| 844 |
elif ext == 'pdf':
|
| 845 |
try:
|
| 846 |
file_bytes = file.read()
|
|
|
|
| 850 |
reader = PyPDF2.PdfReader(pdf_file, strict=False)
|
| 851 |
|
| 852 |
pc = len(reader.pages)
|
| 853 |
+
st.write(f"PDF νμΌ: {pc}νμ΄μ§")
|
| 854 |
|
| 855 |
if pc > 0:
|
| 856 |
try:
|
| 857 |
page_text = reader.pages[0].extract_text()
|
| 858 |
+
preview = page_text[:500] if page_text else "(ν
μ€νΈ μΆμΆ λΆκ°)"
|
| 859 |
+
st.text_area("첫 νμ΄μ§ 미리보기", preview + "...", height=150)
|
| 860 |
except:
|
| 861 |
+
st.warning("첫 νμ΄μ§ ν
μ€νΈ μΆμΆ μ€ν¨")
|
| 862 |
except Exception as e:
|
| 863 |
+
st.error(f"PDF 미리보기 μ€ν¨: {e}")
|
| 864 |
|
| 865 |
if idx < file_count - 1:
|
| 866 |
st.divider()
|
|
|
|
| 872 |
|
| 873 |
# Videos
|
| 874 |
if "videos" in m and m["videos"]:
|
| 875 |
+
st.subheader("κ΄λ ¨ λΉλμ€")
|
| 876 |
for video in m["videos"]:
|
| 877 |
+
video_title = video.get('title', 'κ΄λ ¨ λΉλμ€')
|
| 878 |
video_url = video.get('url', '')
|
| 879 |
thumbnail = video.get('thumbnail', '')
|
| 880 |
|
|
|
|
| 884 |
st.write("π¬")
|
| 885 |
with col2:
|
| 886 |
st.markdown(f"**[{video_title}]({video_url})**")
|
| 887 |
+
st.write(f"μΆμ²: {video.get('source', 'μ μ μμ')}")
|
| 888 |
else:
|
| 889 |
st.markdown(f"π¬ **[{video_title}]({video_url})**")
|
| 890 |
+
st.write(f"μΆμ²: {video.get('source', 'μ μ μμ')}")
|
| 891 |
|
| 892 |
# User input
|
| 893 |
+
query = st.chat_input("λμ°λ¬Ό κ°κ²©, μμ λλ μμ₯ λν₯ κ΄λ ¨ μ§λ¬Έμ μ
λ ₯νμΈμ.")
|
| 894 |
if query:
|
| 895 |
process_input(query, uploaded_files)
|
| 896 |
|
|
|
|
| 916 |
has_uploaded_files = bool(uploaded_files) and len(uploaded_files) > 0
|
| 917 |
|
| 918 |
try:
|
| 919 |
+
status = st.status("μ§λ¬Έμ λ΅λ³ μ€λΉ μ€...")
|
| 920 |
+
status.update(label="ν΄λΌμ΄μΈνΈ μ΄κΈ°ν μ€...")
|
| 921 |
|
| 922 |
client = get_openai_client()
|
| 923 |
|
|
|
|
| 925 |
video_results = []
|
| 926 |
news_results = []
|
| 927 |
|
| 928 |
+
# λμ
λ°μ΄ν°μ
λΆμ κ²°κ³Ό κ°μ Έμ€κΈ°
|
| 929 |
+
status.update(label="λμ
λ°μ΄ν°μ
λΆμ μ€...")
|
| 930 |
+
with st.spinner("λ°μ΄ν°μ
λΆμ μ€..."):
|
| 931 |
+
dataset_analysis = analyze_dataset_for_query(query)
|
| 932 |
+
|
| 933 |
if use_web_search:
|
| 934 |
+
status.update(label="μΉ κ²μ μν μ€...")
|
| 935 |
+
with st.spinner("μΉ κ²μ μ€..."):
|
| 936 |
search_content = do_web_search(keywords(query, top=5))
|
| 937 |
|
| 938 |
try:
|
| 939 |
+
status.update(label="λΉλμ€ κ²μ μ€...")
|
| 940 |
video_results = brave_video_search(query, 2)
|
| 941 |
news_results = brave_news_search(query, 3)
|
| 942 |
except Exception as search_err:
|
| 943 |
+
logging.error(f"λ―Έλμ΄ κ²μ μ€λ₯: {search_err}")
|
| 944 |
|
| 945 |
file_content = None
|
| 946 |
if has_uploaded_files:
|
| 947 |
+
status.update(label="μ
λ‘λλ νμΌ μ²λ¦¬ μ€...")
|
| 948 |
+
with st.spinner("νμΌ λΆμ μ€..."):
|
| 949 |
file_content = process_uploaded_files(uploaded_files)
|
| 950 |
|
| 951 |
valid_videos = []
|
|
|
|
| 954 |
if url and url.startswith('http'):
|
| 955 |
valid_videos.append({
|
| 956 |
'url': url,
|
| 957 |
+
'title': vid.get('title', 'λΉλμ€'),
|
| 958 |
'thumbnail': vid.get('thumbnail_url', ''),
|
| 959 |
+
'source': vid.get('source', 'λΉλμ€ μΆμ²')
|
| 960 |
})
|
| 961 |
|
| 962 |
+
status.update(label="μ’
ν© λΆμ μ€λΉ μ€...")
|
| 963 |
sys_prompt = get_system_prompt(
|
| 964 |
+
mode=st.session_state.analysis_mode,
|
| 965 |
style=st.session_state.response_style,
|
| 966 |
include_search_results=use_web_search,
|
| 967 |
include_uploaded_files=has_uploaded_files
|
|
|
|
| 972 |
]
|
| 973 |
|
| 974 |
user_content = query
|
| 975 |
+
# νμ λ°μ΄ν°μ
λΆμ κ²°κ³Ό ν¬ν¨
|
| 976 |
+
user_content += "\n\n" + dataset_analysis
|
| 977 |
+
|
| 978 |
if search_content:
|
| 979 |
user_content += "\n\n" + search_content
|
| 980 |
if file_content:
|
| 981 |
user_content += "\n\n" + file_content
|
| 982 |
|
| 983 |
if valid_videos:
|
| 984 |
+
user_content += "\n\n# κ΄λ ¨ λμμ\n"
|
| 985 |
for i, vid in enumerate(valid_videos):
|
| 986 |
user_content += f"\n{i+1}. **{vid['title']}** - [{vid['source']}]({vid['url']})\n"
|
| 987 |
|
|
|
|
| 1006 |
message_placeholder.markdown(full_response, unsafe_allow_html=True)
|
| 1007 |
|
| 1008 |
if valid_videos:
|
| 1009 |
+
st.subheader("κ΄λ ¨ λΉλμ€")
|
| 1010 |
for video in valid_videos:
|
| 1011 |
+
video_title = video.get('title', 'κ΄λ ¨ λΉλμ€')
|
| 1012 |
video_url = video.get('url', '')
|
| 1013 |
|
| 1014 |
st.markdown(f"π¬ **[{video_title}]({video_url})**")
|
| 1015 |
+
st.write(f"μΆμ²: {video.get('source', 'μ μ μμ')}")
|
| 1016 |
|
| 1017 |
+
status.update(label="μλ΅ μλ£!", state="complete")
|
| 1018 |
|
| 1019 |
st.session_state.messages.append({
|
| 1020 |
"role": "assistant",
|
|
|
|
| 1024 |
|
| 1025 |
except Exception as api_error:
|
| 1026 |
error_message = str(api_error)
|
| 1027 |
+
logging.error(f"API μ€λ₯: {error_message}")
|
| 1028 |
+
status.update(label=f"μ€λ₯: {error_message}", state="error")
|
| 1029 |
+
raise Exception(f"μλ΅ μμ± μ€λ₯: {error_message}")
|
| 1030 |
|
| 1031 |
if st.session_state.generate_image and full_response:
|
| 1032 |
+
with st.spinner("λ§μΆ€ν μ΄λ―Έμ§ μμ± μ€..."):
|
| 1033 |
try:
|
| 1034 |
ip = extract_image_prompt(full_response, query)
|
| 1035 |
img, cap = generate_image(ip)
|
| 1036 |
if img:
|
| 1037 |
+
st.subheader("AI μμ± μ΄λ―Έμ§")
|
| 1038 |
st.image(img, caption=cap, use_container_width=True)
|
| 1039 |
except Exception as img_error:
|
| 1040 |
+
logging.error(f"μ΄λ―Έμ§ μμ± μ€λ₯: {str(img_error)}")
|
| 1041 |
+
st.warning("λ§μΆ€ν μ΄λ―Έμ§ μμ±μ μ€ν¨νμ΅λλ€.")
|
| 1042 |
|
| 1043 |
if full_response:
|
| 1044 |
+
st.subheader("μ΄ μλ΅ λ€μ΄λ‘λ")
|
| 1045 |
c1, c2 = st.columns(2)
|
| 1046 |
c1.download_button(
|
| 1047 |
+
"λ§ν¬λ€μ΄",
|
| 1048 |
data=full_response,
|
| 1049 |
file_name=f"{query[:30]}.md",
|
| 1050 |
mime="text/markdown"
|
|
|
|
| 1062 |
with open(fn, "w", encoding="utf-8") as fp:
|
| 1063 |
json.dump(st.session_state.messages, fp, ensure_ascii=False, indent=2)
|
| 1064 |
except Exception as e:
|
| 1065 |
+
logging.error(f"μλ μ μ₯ μ€ν¨: {e}")
|
| 1066 |
|
| 1067 |
except Exception as e:
|
| 1068 |
error_message = str(e)
|
| 1069 |
+
placeholder.error(f"μ€λ₯ λ°μ: {error_message}")
|
| 1070 |
+
logging.error(f"μ
λ ₯ μ²λ¦¬ μ€λ₯: {error_message}")
|
| 1071 |
+
ans = f"μμ² μ²λ¦¬ μ€ μ€λ₯κ° λ°μνμ΅λλ€: {error_message}"
|
| 1072 |
st.session_state.messages.append({"role": "assistant", "content": ans})
|
| 1073 |
|
| 1074 |
# ββββββββββββββββββββββββββββββββ main ββββββββββββββββββββββββββββββββββββ
|
| 1075 |
def main():
|
| 1076 |
+
st.write("==== μ ν리μΌμ΄μ
μμ μκ°:", datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "=====")
|
| 1077 |
+
agricultural_price_forecast_app()
|
| 1078 |
|
| 1079 |
if __name__ == "__main__":
|
| 1080 |
main()
|