Update app.py
Browse files
app.py
CHANGED
@@ -3,6 +3,8 @@ import os
|
|
3 |
import sys
|
4 |
import json
|
5 |
import requests
|
|
|
|
|
6 |
|
7 |
# ํ์ฌ ๋๋ ํ ๋ฆฌ์ ํฐํธ ํ์ผ ๊ฒฝ๋ก ์ค์
|
8 |
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
|
@@ -77,8 +79,88 @@ from wbs_diagram_generator import generate_wbs_diagram
|
|
77 |
|
78 |
from sample_data import CONCEPT_MAP_JSON, SYNOPTIC_CHART_JSON, RADIAL_DIAGRAM_JSON, PROCESS_FLOW_JSON, WBS_DIAGRAM_JSON
|
79 |
|
80 |
-
#
|
81 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
82 |
"""Friendli AI API๋ฅผ ํธ์ถํ์ฌ JSON ์์ฑ"""
|
83 |
token = os.environ.get("FRIENDLI_TOKEN") or "YOUR_FRIENDLI_TOKEN"
|
84 |
url = "https://api.friendli.ai/dedicated/v1/chat/completions"
|
@@ -193,9 +275,16 @@ def call_llm_api(prompt, diagram_type):
|
|
193 |
}"""
|
194 |
}
|
195 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
196 |
system_prompt = f"""You are a helpful assistant that generates JSON structures for diagrams.
|
197 |
{json_guides.get(diagram_type, '')}
|
198 |
-
|
199 |
Important rules:
|
200 |
1. Generate ONLY valid JSON without any explanation or markdown formatting
|
201 |
2. The JSON must follow the EXACT structure shown above - do not change field names
|
@@ -205,7 +294,8 @@ Important rules:
|
|
205 |
6. Ensure all connections reference existing node IDs
|
206 |
7. For Process Flow: 'type' can be: "process", "decision", "start", "end", "io"
|
207 |
8. For nested structures (Concept Map, Synoptic Chart, Radial, WBS), include empty 'subnodes' or 'subtasks' arrays when there are no children
|
208 |
-
9. Do not add any additional fields not shown in the example structure
|
|
|
209 |
|
210 |
payload = {
|
211 |
"model": "dep89a2fld32mcm",
|
@@ -270,13 +360,29 @@ Important rules:
|
|
270 |
print(f"LLM API Error: {str(e)}")
|
271 |
return json.dumps({"error": str(e)})
|
272 |
|
273 |
-
def generate_with_llm(prompt, diagram_type, output_format):
|
274 |
"""LLM์ผ๋ก JSON์ ์์ฑํ๊ณ ๋ค์ด์ด๊ทธ๋จ์ ์์ฑ"""
|
275 |
if not prompt:
|
276 |
-
return None, "Please enter a prompt"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
277 |
|
278 |
-
# LLM์ผ๋ก JSON ์์ฑ
|
279 |
-
generated_json = call_llm_api(prompt, diagram_type)
|
280 |
|
281 |
try:
|
282 |
# JSON ์ ํจ์ฑ ๊ฒ์ฌ
|
@@ -286,13 +392,13 @@ def generate_with_llm(prompt, diagram_type, output_format):
|
|
286 |
# JSON ๊ตฌ์กฐ ๊ฒ์ฆ
|
287 |
if diagram_type in ["Concept Map", "Synoptic Chart", "Radial Diagram"]:
|
288 |
if "central_node" not in json_data or "nodes" not in json_data:
|
289 |
-
return None, f"Invalid JSON structure for {diagram_type}. Missing 'central_node' or 'nodes'. Generated JSON:\n{json_str}"
|
290 |
elif diagram_type == "Process Flow":
|
291 |
if "start_node" not in json_data or "nodes" not in json_data or "connections" not in json_data:
|
292 |
-
return None, f"Invalid JSON structure for Process Flow. Missing 'start_node', 'nodes', or 'connections'. Generated JSON:\n{json_str}"
|
293 |
elif diagram_type == "WBS Diagram":
|
294 |
if "project_title" not in json_data or "phases" not in json_data:
|
295 |
-
return None, f"Invalid JSON structure for WBS. Missing 'project_title' or 'phases'. Generated JSON:\n{json_str}"
|
296 |
|
297 |
# ๋ค์ด์ด๊ทธ๋จ ์์ฑ
|
298 |
try:
|
@@ -307,21 +413,21 @@ def generate_with_llm(prompt, diagram_type, output_format):
|
|
307 |
elif diagram_type == "WBS Diagram":
|
308 |
diagram = generate_wbs_diagram(json_str, output_format)
|
309 |
else:
|
310 |
-
return None, "Invalid diagram type"
|
311 |
|
312 |
# ์๋ฌ ๋ฉ์์ง๊ฐ ๋ฐํ๋ ๊ฒฝ์ฐ
|
313 |
if isinstance(diagram, str) and diagram.startswith("Error:"):
|
314 |
-
return None, f"Diagram generation error: {diagram}\n\nGenerated JSON:\n{json_str}"
|
315 |
|
316 |
-
return diagram, json_str
|
317 |
|
318 |
except Exception as e:
|
319 |
-
return None, f"Error generating diagram: {str(e)}\n\nGenerated JSON:\n{json_str}"
|
320 |
|
321 |
except json.JSONDecodeError as e:
|
322 |
-
return None, f"Invalid JSON generated: {str(e)}\n\nGenerated content:\n{generated_json}"
|
323 |
except Exception as e:
|
324 |
-
return None, f"Unexpected error: {str(e)}\n\nGenerated content:\n{generated_json}"
|
325 |
|
326 |
if __name__ == "__main__":
|
327 |
DEFAULT_BASE_COLOR = '#19191a'
|
@@ -482,6 +588,23 @@ if __name__ == "__main__":
|
|
482 |
margin-bottom: 20px;
|
483 |
}
|
484 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
485 |
/* ๋ฐ์ํ ๋์์ธ */
|
486 |
@media (max-width: 768px) {
|
487 |
.main-container {
|
@@ -541,8 +664,22 @@ if __name__ == "__main__":
|
|
541 |
interactive=True
|
542 |
)
|
543 |
|
|
|
|
|
|
|
|
|
|
|
|
|
544 |
generate_btn = gr.Button("โจ Generate with AI", variant="primary", size="lg")
|
545 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
546 |
generated_json_output = gr.Textbox(
|
547 |
label="๐ Generated JSON",
|
548 |
lines=15,
|
@@ -558,10 +695,20 @@ if __name__ == "__main__":
|
|
558 |
height=600
|
559 |
)
|
560 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
561 |
generate_btn.click(
|
562 |
fn=generate_with_llm,
|
563 |
-
inputs=[prompt_input, diagram_type_select, output_format_radio],
|
564 |
-
outputs=[ai_output_image, generated_json_output]
|
565 |
)
|
566 |
|
567 |
with gr.Row(elem_classes=["panel-section"]):
|
|
|
3 |
import sys
|
4 |
import json
|
5 |
import requests
|
6 |
+
import re
|
7 |
+
from typing import List, Tuple
|
8 |
|
9 |
# ํ์ฌ ๋๋ ํ ๋ฆฌ์ ํฐํธ ํ์ผ ๊ฒฝ๋ก ์ค์
|
10 |
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
|
79 |
|
80 |
from sample_data import CONCEPT_MAP_JSON, SYNOPTIC_CHART_JSON, RADIAL_DIAGRAM_JSON, PROCESS_FLOW_JSON, WBS_DIAGRAM_JSON
|
81 |
|
82 |
+
# ๋ธ๋ ์ด๋ธ ์์น API ํจ์
|
83 |
+
def brave_search(query: str) -> List[dict]:
|
84 |
+
"""๋ธ๋ ์ด๋ธ ์์น API๋ฅผ ์ฌ์ฉํ์ฌ ๊ฒ์ ์ํ"""
|
85 |
+
api_key = os.getenv("BSEARCH_API")
|
86 |
+
if not api_key:
|
87 |
+
print("Warning: BSEARCH_API environment variable not set")
|
88 |
+
return []
|
89 |
+
|
90 |
+
url = "https://api.search.brave.com/res/v1/web/search"
|
91 |
+
headers = {
|
92 |
+
"Accept": "application/json",
|
93 |
+
"X-Subscription-Token": api_key
|
94 |
+
}
|
95 |
+
params = {
|
96 |
+
"q": query,
|
97 |
+
"count": 5 # ์์ 5๊ฐ ๊ฒฐ๊ณผ๋ง ๊ฐ์ ธ์ค๊ธฐ
|
98 |
+
}
|
99 |
+
|
100 |
+
try:
|
101 |
+
response = requests.get(url, headers=headers, params=params, timeout=10)
|
102 |
+
if response.status_code == 200:
|
103 |
+
data = response.json()
|
104 |
+
results = []
|
105 |
+
if "web" in data and "results" in data["web"]:
|
106 |
+
for result in data["web"]["results"][:5]:
|
107 |
+
results.append({
|
108 |
+
"title": result.get("title", ""),
|
109 |
+
"description": result.get("description", ""),
|
110 |
+
"url": result.get("url", "")
|
111 |
+
})
|
112 |
+
return results
|
113 |
+
else:
|
114 |
+
print(f"Brave Search API error: {response.status_code}")
|
115 |
+
return []
|
116 |
+
except Exception as e:
|
117 |
+
print(f"Brave Search error: {str(e)}")
|
118 |
+
return []
|
119 |
+
|
120 |
+
def extract_keywords(prompt: str, diagram_type: str) -> str:
|
121 |
+
"""ํ๋กฌํํธ์์ ํต์ฌ ํค์๋ ์ถ์ถ"""
|
122 |
+
# ๋ค์ด์ด๊ทธ๋จ ํ์
์ ๊ฑฐ
|
123 |
+
prompt_clean = prompt.lower()
|
124 |
+
|
125 |
+
# ์ผ๋ฐ์ ์ธ ์์ฒญ ํํ ์ ๊ฑฐ
|
126 |
+
remove_patterns = [
|
127 |
+
r"create\s+a?\s*", r"make\s+a?\s*", r"generate\s+a?\s*", r"build\s+a?\s*",
|
128 |
+
r"design\s+a?\s*", r"develop\s+a?\s*", r"show\s+me\s*", r"i\s+need\s+a?\s*",
|
129 |
+
r"diagram\s*", r"chart\s*", r"map\s*", r"flow\s*", r"๋ฅผ\s*๋ง๋ค์ด\s*",
|
130 |
+
r"์์ฑํด\s*", r"๊ทธ๋ ค\s*", r"๋ณด์ฌ\s*", r"์ค๊ณ\s*", r"๊ตฌ์ถ\s*"
|
131 |
+
]
|
132 |
+
|
133 |
+
for pattern in remove_patterns:
|
134 |
+
prompt_clean = re.sub(pattern, "", prompt_clean)
|
135 |
+
|
136 |
+
# ์ฃผ์ ๋ช
์ฌ์ ํต์ฌ ์ฉ์ด๋ง ์ถ์ถ
|
137 |
+
# ๊ฐ๋จํ ๋ฐฉ๋ฒ: ๊ธธ์ด๊ฐ 3์ ์ด์์ธ ๋จ์ด๋ค์ ์ถ์ถ
|
138 |
+
words = prompt_clean.split()
|
139 |
+
keywords = []
|
140 |
+
|
141 |
+
for word in words:
|
142 |
+
# ๋ถํ์ํ ๋จ์ด ์ ์ธ
|
143 |
+
if len(word) > 2 and word not in ["the", "and", "for", "with", "that", "this", "from", "about"]:
|
144 |
+
keywords.append(word)
|
145 |
+
|
146 |
+
# ์ต๋ 5๊ฐ ํค์๋๋ง ์ฌ์ฉ
|
147 |
+
return " ".join(keywords[:5])
|
148 |
+
|
149 |
+
def enrich_prompt_with_search(prompt: str, diagram_type: str, search_results: List[dict]) -> str:
|
150 |
+
"""๊ฒ์ ๊ฒฐ๊ณผ๋ฅผ ๋ฐํ์ผ๋ก ํ๋กฌํํธ๋ฅผ ๋ณด๊ฐ"""
|
151 |
+
if not search_results:
|
152 |
+
return prompt
|
153 |
+
|
154 |
+
# ๊ฒ์ ๊ฒฐ๊ณผ์์ ์ ์ฉํ ์ ๋ณด ์ถ์ถ
|
155 |
+
enrichment = "\n\nAdditional context from web search:\n"
|
156 |
+
for i, result in enumerate(search_results[:3]): # ์์ 3๊ฐ๋ง ์ฌ์ฉ
|
157 |
+
enrichment += f"- {result['title']}: {result['description']}\n"
|
158 |
+
|
159 |
+
enriched_prompt = f"{prompt}{enrichment}"
|
160 |
+
return enriched_prompt
|
161 |
+
|
162 |
+
# LLM API ํจ์ ์์
|
163 |
+
def call_llm_api(prompt, diagram_type, use_search=False, search_results=None):
|
164 |
"""Friendli AI API๋ฅผ ํธ์ถํ์ฌ JSON ์์ฑ"""
|
165 |
token = os.environ.get("FRIENDLI_TOKEN") or "YOUR_FRIENDLI_TOKEN"
|
166 |
url = "https://api.friendli.ai/dedicated/v1/chat/completions"
|
|
|
275 |
}"""
|
276 |
}
|
277 |
|
278 |
+
# ๊ฒ์ ๊ฒฐ๊ณผ๊ฐ ์์ผ๋ฉด ์์คํ
ํ๋กฌํํธ์ ์ถ๊ฐ
|
279 |
+
search_context = ""
|
280 |
+
if use_search and search_results:
|
281 |
+
search_context = "\n\nUse the following search results to enrich the diagram content:\n"
|
282 |
+
for result in search_results[:3]:
|
283 |
+
search_context += f"- {result['title']}: {result['description']}\n"
|
284 |
+
|
285 |
system_prompt = f"""You are a helpful assistant that generates JSON structures for diagrams.
|
286 |
{json_guides.get(diagram_type, '')}
|
287 |
+
{search_context}
|
288 |
Important rules:
|
289 |
1. Generate ONLY valid JSON without any explanation or markdown formatting
|
290 |
2. The JSON must follow the EXACT structure shown above - do not change field names
|
|
|
294 |
6. Ensure all connections reference existing node IDs
|
295 |
7. For Process Flow: 'type' can be: "process", "decision", "start", "end", "io"
|
296 |
8. For nested structures (Concept Map, Synoptic Chart, Radial, WBS), include empty 'subnodes' or 'subtasks' arrays when there are no children
|
297 |
+
9. Do not add any additional fields not shown in the example structure
|
298 |
+
10. If search results are provided, incorporate relevant information into the diagram content"""
|
299 |
|
300 |
payload = {
|
301 |
"model": "dep89a2fld32mcm",
|
|
|
360 |
print(f"LLM API Error: {str(e)}")
|
361 |
return json.dumps({"error": str(e)})
|
362 |
|
363 |
+
def generate_with_llm(prompt, diagram_type, output_format, use_search):
|
364 |
"""LLM์ผ๋ก JSON์ ์์ฑํ๊ณ ๋ค์ด์ด๊ทธ๋จ์ ์์ฑ"""
|
365 |
if not prompt:
|
366 |
+
return None, "Please enter a prompt", ""
|
367 |
+
|
368 |
+
search_results = []
|
369 |
+
search_info = ""
|
370 |
+
|
371 |
+
# ๋ธ๋ ์ด๋ธ ์์น ์ฌ์ฉ ์
|
372 |
+
if use_search:
|
373 |
+
keywords = extract_keywords(prompt, diagram_type)
|
374 |
+
if keywords:
|
375 |
+
search_info = f"๐ Searching for: {keywords}\n"
|
376 |
+
search_results = brave_search(keywords)
|
377 |
+
if search_results:
|
378 |
+
search_info += f"โ
Found {len(search_results)} relevant results\n\n"
|
379 |
+
for i, result in enumerate(search_results[:3]):
|
380 |
+
search_info += f"{i+1}. {result['title']}\n {result['description'][:100]}...\n\n"
|
381 |
+
else:
|
382 |
+
search_info += "โ No search results found\n\n"
|
383 |
|
384 |
+
# LLM์ผ๋ก JSON ์์ฑ (๊ฒ์ ๊ฒฐ๊ณผ ํฌํจ)
|
385 |
+
generated_json = call_llm_api(prompt, diagram_type, use_search, search_results)
|
386 |
|
387 |
try:
|
388 |
# JSON ์ ํจ์ฑ ๊ฒ์ฌ
|
|
|
392 |
# JSON ๊ตฌ์กฐ ๊ฒ์ฆ
|
393 |
if diagram_type in ["Concept Map", "Synoptic Chart", "Radial Diagram"]:
|
394 |
if "central_node" not in json_data or "nodes" not in json_data:
|
395 |
+
return None, f"Invalid JSON structure for {diagram_type}. Missing 'central_node' or 'nodes'. Generated JSON:\n{json_str}", search_info
|
396 |
elif diagram_type == "Process Flow":
|
397 |
if "start_node" not in json_data or "nodes" not in json_data or "connections" not in json_data:
|
398 |
+
return None, f"Invalid JSON structure for Process Flow. Missing 'start_node', 'nodes', or 'connections'. Generated JSON:\n{json_str}", search_info
|
399 |
elif diagram_type == "WBS Diagram":
|
400 |
if "project_title" not in json_data or "phases" not in json_data:
|
401 |
+
return None, f"Invalid JSON structure for WBS. Missing 'project_title' or 'phases'. Generated JSON:\n{json_str}", search_info
|
402 |
|
403 |
# ๋ค์ด์ด๊ทธ๋จ ์์ฑ
|
404 |
try:
|
|
|
413 |
elif diagram_type == "WBS Diagram":
|
414 |
diagram = generate_wbs_diagram(json_str, output_format)
|
415 |
else:
|
416 |
+
return None, "Invalid diagram type", search_info
|
417 |
|
418 |
# ์๋ฌ ๋ฉ์์ง๊ฐ ๋ฐํ๋ ๊ฒฝ์ฐ
|
419 |
if isinstance(diagram, str) and diagram.startswith("Error:"):
|
420 |
+
return None, f"Diagram generation error: {diagram}\n\nGenerated JSON:\n{json_str}", search_info
|
421 |
|
422 |
+
return diagram, json_str, search_info
|
423 |
|
424 |
except Exception as e:
|
425 |
+
return None, f"Error generating diagram: {str(e)}\n\nGenerated JSON:\n{json_str}", search_info
|
426 |
|
427 |
except json.JSONDecodeError as e:
|
428 |
+
return None, f"Invalid JSON generated: {str(e)}\n\nGenerated content:\n{generated_json}", search_info
|
429 |
except Exception as e:
|
430 |
+
return None, f"Unexpected error: {str(e)}\n\nGenerated content:\n{generated_json}", search_info
|
431 |
|
432 |
if __name__ == "__main__":
|
433 |
DEFAULT_BASE_COLOR = '#19191a'
|
|
|
588 |
margin-bottom: 20px;
|
589 |
}
|
590 |
|
591 |
+
/* ๊ฒ์ ์ ๋ณด ์คํ์ผ */
|
592 |
+
.search-info {
|
593 |
+
background: #f8f9fa;
|
594 |
+
padding: 15px;
|
595 |
+
border-radius: 10px;
|
596 |
+
margin-top: 10px;
|
597 |
+
border-left: 4px solid #667eea;
|
598 |
+
}
|
599 |
+
|
600 |
+
/* ์ฒดํฌ๋ฐ์ค ์คํ์ผ */
|
601 |
+
.gr-checkbox {
|
602 |
+
margin-top: 15px;
|
603 |
+
padding: 10px;
|
604 |
+
background: #f8f9fa;
|
605 |
+
border-radius: 8px;
|
606 |
+
}
|
607 |
+
|
608 |
/* ๋ฐ์ํ ๋์์ธ */
|
609 |
@media (max-width: 768px) {
|
610 |
.main-container {
|
|
|
664 |
interactive=True
|
665 |
)
|
666 |
|
667 |
+
use_search_checkbox = gr.Checkbox(
|
668 |
+
label="๐ Use Brave Search to enhance content",
|
669 |
+
value=False,
|
670 |
+
info="Search the web for relevant information to enrich your diagram"
|
671 |
+
)
|
672 |
+
|
673 |
generate_btn = gr.Button("โจ Generate with AI", variant="primary", size="lg")
|
674 |
|
675 |
+
search_info_output = gr.Textbox(
|
676 |
+
label="๐ Search Information",
|
677 |
+
lines=8,
|
678 |
+
interactive=False,
|
679 |
+
visible=False,
|
680 |
+
elem_classes=["search-info"]
|
681 |
+
)
|
682 |
+
|
683 |
generated_json_output = gr.Textbox(
|
684 |
label="๐ Generated JSON",
|
685 |
lines=15,
|
|
|
695 |
height=600
|
696 |
)
|
697 |
|
698 |
+
# ๊ฒ์ ์ฒดํฌ๋ฐ์ค ๋ณ๊ฒฝ ์ ๊ฒ์ ์ ๋ณด ์ถ๋ ฅ ํ์/์จ๊น
|
699 |
+
def toggle_search_info(use_search):
|
700 |
+
return gr.update(visible=use_search)
|
701 |
+
|
702 |
+
use_search_checkbox.change(
|
703 |
+
fn=toggle_search_info,
|
704 |
+
inputs=[use_search_checkbox],
|
705 |
+
outputs=[search_info_output]
|
706 |
+
)
|
707 |
+
|
708 |
generate_btn.click(
|
709 |
fn=generate_with_llm,
|
710 |
+
inputs=[prompt_input, diagram_type_select, output_format_radio, use_search_checkbox],
|
711 |
+
outputs=[ai_output_image, generated_json_output, search_info_output]
|
712 |
)
|
713 |
|
714 |
with gr.Row(elem_classes=["panel-section"]):
|