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()