kimhyunwoo commited on
Commit
b328beb
ยท
verified ยท
1 Parent(s): db2f9f4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -63
app.py CHANGED
@@ -23,7 +23,7 @@ def call_mistral_api(messages):
23
  except requests.exceptions.RequestException as e:
24
  return f"API Call Error: {e}"
25
 
26
- # --- 2. ๋ฐฑ์—”๋“œ ํ•ต์‹ฌ ๊ธฐ๋Šฅ (ํŒŒ์„œ ์ถ”๊ฐ€) ---
27
  def parse_code_from_response(response_text: str) -> str | None:
28
  """LLM ์‘๋‹ต์—์„œ C ์ฝ”๋“œ ๋ธ”๋ก์„ ์ถ”์ถœํ•ฉ๋‹ˆ๋‹ค."""
29
  match = re.search(r'```c\n(.*?)\n```', response_text, re.DOTALL)
@@ -31,6 +31,10 @@ def parse_code_from_response(response_text: str) -> str | None:
31
  return match.group(1).strip()
32
  return None
33
 
 
 
 
 
34
  def compile_and_run_c_code(code: str) -> str:
35
  try:
36
  with open("main.c", "w", encoding='utf-8') as f: f.write(code)
@@ -42,73 +46,55 @@ def compile_and_run_c_code(code: str) -> str:
42
  return f"--- EXECUTION SUCCEEDED ---\n{output}" if output.strip() else "--- EXECUTION SUCCEEDED ---\n(No output was produced)"
43
  except Exception as e: return f"--- SYSTEM ERROR ---\nAn unexpected error occurred: {str(e)}"
44
 
45
- # --- 3. ์ง„์งœ '์ง€๋Šฅํ˜•' ์—์ด์ „ํŠธ ๋กœ์ง ---
46
- def intelligent_agent(code: str, instruction: str):
47
- if not instruction:
48
- yield code, "Error: Instruction cannot be empty."
49
- return
50
-
51
- lower_instruction = instruction.lower()
52
 
53
- # 1. ์ƒ์„ฑ (Generation)
54
- if "generate" in lower_instruction or "create" in lower_instruction or "๋งŒ๋“ค์–ด์ค˜" in lower_instruction:
55
- yield code, "1. Generating new code..."
56
- prompt = f"You are a C programming expert. Generate a complete, compilable C code for this request: '{instruction}'. ONLY output the raw C code, without any markdown formatting or explanations."
57
- new_code = call_mistral_api([{"role": "user", "content": prompt}])
58
- yield new_code, "2. Code generation successful. The new code is now in the editor."
59
- return
60
-
61
- if not code:
62
- yield code, "Error: Code editor is empty. Please provide code or ask to 'generate' it."
63
- return
64
 
65
- # 2. ๋ถ„์„/๋ฆฌํŒฉํ† ๋ง (Analyze/Refactor)
66
- if any(keyword in lower_instruction for keyword in ["analyze", "refactor", "explain", "comment", "review", "๊ฐœ์„ ", "์„ค๋ช…", "๋ฒ„๊ทธ"]):
67
- yield code, f"1. Analyzing code with instruction: '{instruction}'..."
68
- prompt = f"You are a senior C code reviewer. Fulfill this instruction: '{instruction}'. If you refactor the code, YOU MUST provide the complete, improved code in a ```c code block. \n\nC Code to Analyze:\n```c\n{code}\n```"
69
- analysis_result = call_mistral_api([{"role": "user", "content": prompt}])
70
-
71
- # ์ง€๋Šฅํ˜• ํŒŒ์‹ฑ: ๋ฆฌํŒฉํ† ๋ง๋œ ์ฝ”๋“œ๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธ
72
- refactored_code = parse_code_from_response(analysis_result)
73
- if refactored_code:
74
- yield refactored_code, f"2. Refactoring successful. Code editor updated.\n\n{analysis_result}"
75
- # 'and compile' ๊ฐ™์€ ํ›„์† ๋ช…๋ น์ด ์žˆ๋Š”์ง€ ํ™•์ธ
76
- if "compile" in lower_instruction or "run" in lower_instruction:
77
- yield refactored_code, "3. Compiling the new code..."
78
- compile_result = compile_and_run_c_code(refactored_code)
79
- yield refactored_code, f"4. Compilation finished.\n\n{compile_result}"
80
- else:
81
- # ๋ฆฌํŒฉํ† ๋ง๋œ ์ฝ”๋“œ๊ฐ€ ์—†์œผ๋ฉด, ๋ถ„์„ ๊ฒฐ๊ณผ๋งŒ ๋ณด์—ฌ์คŒ
82
- yield code, f"2. Analysis complete.\n\n{analysis_result}"
83
- return
84
 
85
- # 3. ์ปดํŒŒ์ผ ๋ฐ ์‹คํ–‰ (Compile & Run)
86
- if "compile" in lower_instruction or "run" in lower_instruction:
87
- yield code, "1. Compiling and running..."
88
- result = compile_and_run_c_code(code)
89
- yield code, f"2. Process finished.\n\n{result}"
90
- return
91
-
92
- # 4. ๊ทธ ์™ธ
93
- yield code, "Error: Could not understand the instruction. Please be more specific (e.g., 'generate', 'compile', 'refactor')."
 
 
 
 
 
 
 
 
94
 
95
- # --- 4. ํ†ตํ•ฉ๋œ Gradio UI ---
96
- with gr.Blocks(theme=gr.themes.Monochrome(primary_hue="indigo", secondary_hue="blue"), css="footer {visibility: hidden}") as demo:
97
- gr.Markdown("# ๐Ÿ’ป The True C-Codestral IDE Agent")
98
-
99
- with gr.Row():
100
- with gr.Column(scale=2):
101
- code_editor = gr.Code(label="C Code Editor", language="c", lines=25, interactive=True, value='#include <stdio.h>\n\nint main() {\n printf("Hello, World!\\n");\n return 0;\n}')
102
- with gr.Column(scale=1):
103
- instruction_box = gr.Textbox(label="Instruction", placeholder="e.g., 'Refactor this code and run it', 'Generate a factorial function', 'Find bugs'...", lines=4)
104
- execute_btn = gr.Button("Execute", variant="primary", size="lg")
105
- output_box = gr.Markdown(label="Console / Output", value="Welcome! Enter an instruction and press 'Execute'.")
106
 
107
- execute_btn.click(
108
- fn=intelligent_agent,
109
- inputs=[code_editor, instruction_box],
110
- outputs=[code_editor, output_box]
111
- )
 
 
 
 
 
 
112
 
113
  if __name__ == "__main__":
114
  demo.queue().launch()
 
23
  except requests.exceptions.RequestException as e:
24
  return f"API Call Error: {e}"
25
 
26
+ # --- 2. ๋ฐฑ์—”๋“œ ํ•ต์‹ฌ ๊ธฐ๋Šฅ ํ•จ์ˆ˜ ---
27
  def parse_code_from_response(response_text: str) -> str | None:
28
  """LLM ์‘๋‹ต์—์„œ C ์ฝ”๋“œ ๋ธ”๋ก์„ ์ถ”์ถœํ•ฉ๋‹ˆ๋‹ค."""
29
  match = re.search(r'```c\n(.*?)\n```', response_text, re.DOTALL)
 
31
  return match.group(1).strip()
32
  return None
33
 
34
+ def generate_c_code(description: str) -> str:
35
+ prompt = f"You are a C programming expert. Generate a complete, compilable C code for this request: '{description}'. ONLY output the raw C code, without any markdown formatting or explanations."
36
+ return call_mistral_api([{"role": "user", "content": prompt}])
37
+
38
  def compile_and_run_c_code(code: str) -> str:
39
  try:
40
  with open("main.c", "w", encoding='utf-8') as f: f.write(code)
 
46
  return f"--- EXECUTION SUCCEEDED ---\n{output}" if output.strip() else "--- EXECUTION SUCCEEDED ---\n(No output was produced)"
47
  except Exception as e: return f"--- SYSTEM ERROR ---\nAn unexpected error occurred: {str(e)}"
48
 
49
+ def analyze_and_refactor_code(code: str, instruction: str):
50
+ prompt = f""You are a senior C code reviewer. Fulfill this instruction: '{instruction}'. If you refactor the code, YOU MUST provide the complete, improved code in a ```c code block. \n\nC Code to Analyze:\n```c\n{code}\n```""
51
+ analysis_result = call_mistral_api([{"role": "user", "content": prompt}])
 
 
 
 
52
 
53
+ # ์ง€๋Šฅํ˜• ํŒŒ์‹ฑ: ๋ฆฌํŒฉํ† ๋ง๋œ ์ฝ”๋“œ๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธ
54
+ refactored_code = parse_code_from_response(analysis_result)
55
+
56
+ if refactored_code:
57
+ # ๋ฆฌํŒฉํ† ๋ง๋œ ์ฝ”๋“œ๊ฐ€ ์žˆ์œผ๋ฉด, ๊ทธ ์ฝ”๋“œ๋ฅผ ์—๋””ํ„ฐ์—, ์ „์ฒด ์‘๋‹ต์„ ๊ฒฐ๊ณผ์ฐฝ์— ๋ฐ˜ํ™˜
58
+ return refactored_code, analysis_result
59
+ else:
60
+ # ๋ฆฌํŒฉํ† ๋ง๋œ ์ฝ”๋“œ๊ฐ€ ์—†์œผ๋ฉด, ์›๋ž˜ ์ฝ”๋“œ๋Š” ๊ทธ๋Œ€๋กœ ๋‘๊ณ , ๋ถ„์„ ๊ฒฐ๊ณผ๋งŒ ๋ฐ˜ํ™˜
61
+ return code, analysis_result
 
 
62
 
63
+ # --- 3. Gradio UI ๊ตฌ์„ฑ (์•ˆ์ •์ ์ธ ํƒญ ๊ตฌ์กฐ + ์ง€๋Šฅํ˜• ํŒŒ์‹ฑ) ---
64
+ with gr.Blocks(theme=gr.themes.Monochrome(primary_hue="indigo", secondary_hue="blue"), css="footer {visibility: hidden}") as demo:
65
+ gr.Markdown("# ๐Ÿ’ป The C-Codestral IDE Agent (Stable Tabbed Version)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
+ with gr.Tabs():
68
+ with gr.TabItem("๐Ÿ‘จโ€๐Ÿ’ป IDE"):
69
+ with gr.Row():
70
+ with gr.Column(scale=2):
71
+ code_editor = gr.Code(label="C Code Editor", language="c", lines=20, interactive=True, value='#include <stdio.h>\n\nint main() {\n printf("Hello, World!\\n");\n return 0;\n}')
72
+
73
+ with gr.Column(scale=1):
74
+ # ๋ช…๋ น์–ด ํƒญ ๊ตฌ์„ฑ
75
+ with gr.Tabs():
76
+ with gr.TabItem("Generate"):
77
+ gen_instr = gr.Textbox(label="Generation Instruction", placeholder="e.g., 'a program that calculates factorial'")
78
+ gen_btn = gr.Button("Generate Code", variant="primary")
79
+ with gr.TabItem("Analyze / Refactor"):
80
+ ana_instr = gr.Textbox(label="Analysis Instruction", placeholder="e.g., 'add comments', 'refactor for efficiency'")
81
+ ana_btn = gr.Button("Analyze / Refactor", variant="primary")
82
+ with gr.TabItem("Compile / Run"):
83
+ run_btn = gr.Button("Compile and Run", variant="stop")
84
 
85
+ output_box = gr.Textbox(label="Output / Console", lines=8, interactive=False, show_copy_button=True)
 
 
 
 
 
 
 
 
 
 
86
 
87
+ # ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ ์—ฐ๊ฒฐ
88
+ gen_btn.click(fn=generate_c_code, inputs=[gen_instr], outputs=[code_editor])
89
+ ana_btn.click(fn=analyze_and_refactor_code, inputs=[code_editor, ana_instr], outputs=[code_editor, output_box])
90
+ run_btn.click(fn=compile_and_run_c_code, inputs=[code_editor], outputs=[output_box])
91
+
92
+ with gr.TabItem("๐Ÿ› ๏ธ MCP Tools"):
93
+ gr.Markdown("## Available MCP Tools for other Agents")
94
+ with gr.Accordion("Tool: Generate C Code", open=False):
95
+ gr.Interface(fn=generate_c_code, inputs="text", outputs=gr.Code(language="c", label="Generated C Code"))
96
+ with gr.Accordion("Tool: Compile & Run C Code", open=False):
97
+ gr.Interface(fn=compile_and_run_c_code, inputs=gr.Code(language="c"), outputs=gr.Textbox(label="Output"))
98
 
99
  if __name__ == "__main__":
100
  demo.queue().launch()