CultriX commited on
Commit
cd4b4ee
·
verified ·
1 Parent(s): 0db2f97

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -47
app.py CHANGED
@@ -18,7 +18,6 @@ class NordTheme(Base):
18
  font_mono=(fonts.GoogleFont("Fira Code"), "ui-monospace", "monospace"),
19
  )
20
  self.set(
21
- # Color Palette
22
  body_background_fill="#2E3440",
23
  body_text_color="#ECEFF4",
24
  block_background_fill="#3B4252",
@@ -26,37 +25,27 @@ class NordTheme(Base):
26
  block_border_color="#4C566A",
27
  block_label_background_fill="#434C5E",
28
  block_label_text_color="#ECEFF4",
29
-
30
  input_background_fill="#434C5E",
31
  input_border_color="transparent",
32
- input_text_color="#ECEFF4",
33
-
34
- # Button Styles
35
  button_primary_background_fill="#5E81AC",
36
  button_primary_background_fill_hover="#81A1C1",
37
  button_primary_text_color="#ECEFF4",
38
  button_secondary_background_fill="#4C566A",
39
  button_secondary_background_fill_hover="#5a657a",
40
  button_secondary_text_color="#ECEFF4",
41
-
42
- # Other Elements
43
  border_color_accent="#5E81AC",
44
  background_fill_primary_dark="#2E3440",
45
  color_accent_soft="#4c566a",
46
-
47
- # Sizing
48
- radius_sm=sizes.radius_sm,
49
- radius_md=sizes.radius_md,
50
- radius_lg=sizes.radius_lg,
51
  block_radius="12px",
52
  button_radius="8px",
53
  )
54
 
55
  # --- UI Configuration ---
56
 
 
57
  LANGUAGES = [
58
- 'Python', 'JavaScript', 'TypeScript', 'Java', 'C++', 'C#', 'C', 'Go',
59
- 'Rust', 'Swift', 'Kotlin', 'PHP', 'Ruby', 'Scala', 'R', 'MATLAB',
60
  'Perl', 'Haskell', 'Lua', 'Dart', 'Elixir', 'F#', 'Clojure', 'SQL'
61
  ]
62
 
@@ -83,22 +72,52 @@ print(fibonacci(10))"""
83
  def convert_code(
84
  source_code: str, source_lang: str, target_lang: str, model: str, api_key: str
85
  ):
 
 
 
 
 
 
86
  if not source_code.strip():
87
- raise gr.Error("Please enter some code to convert.")
88
  if not api_key.strip():
89
  raise gr.Error("OpenRouter API key is required.")
90
  if not model or not model.strip():
91
  raise gr.Error("Please select or enter a model for the conversion.")
 
 
 
 
92
 
93
  client = openai.OpenAI(base_url="https://openrouter.ai/api/v1", api_key=api_key)
94
- prompt = (
95
- f"You are an expert programmer. Convert the following {source_lang} code "
96
- f"to {target_lang}. Your response should only contain the raw, converted code. "
97
- "Do not include any explanations, markdown formatting (like ```), or extra text."
98
- f"\n\n--- Start of {source_lang} Code ---\n"
99
- f"{source_code}\n"
100
- f"--- End of {source_lang} Code ---"
101
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  try:
103
  completion = client.chat.completions.create(
104
  model=model,
@@ -113,49 +132,43 @@ def convert_code(
113
 
114
  # --- Gradio User Interface ---
115
 
 
 
 
 
 
 
116
  with gr.Blocks(theme=NordTheme()) as app:
117
  # Header
118
  gr.HTML(
119
  """
120
  <div style="display: flex; align-items: center; gap: 12px; padding: 10px;">
121
- <svg xmlns="[http://www.w3.org/2000/svg](http://www.w3.org/2000/svg)" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#81A1C1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m18 16 4-4-4-4"/><path d="m6 8-4 4 4 4"/><path d="m14.5 4-5 16"/></svg>
122
  <div>
123
  <h1 style="font-size: 1.5rem; font-weight: 700; color: #ECEFF4; margin: 0;">CodeVerter</h1>
124
- <p style="font-size: 0.875rem; color: #D8DEE9; margin: 0;">Programming Language Converter via OpenRouter</p>
125
  </div>
126
  </div>
127
  """
128
  )
129
 
130
- # Configuration Accordion
131
  with gr.Accordion("⚙️ Configuration", open=True):
132
- openrouter_key = gr.Textbox(
133
- label="OpenRouter API Key",
134
- placeholder="Enter your OpenRouter API key...",
135
- type="password",
136
- )
137
- model_selection = gr.Dropdown(
138
- label="Select or Enter a Model Name",
139
- choices=MODELS,
140
- value=MODELS[0] if MODELS else None,
141
- allow_custom_value=True,
142
- )
143
 
144
- # Main conversion interface
145
  with gr.Row(equal_height=False):
146
  with gr.Column(scale=1):
147
  source_lang_selection = gr.Dropdown(label="Source Language", choices=LANGUAGES, value="Python")
148
- source_code_input = gr.Code(label="Source Code", language="python", value=DEFAULT_SOURCE_CODE, lines=15)
149
  with gr.Column(scale=1):
150
  target_lang_selection = gr.Dropdown(label="Target Language", choices=LANGUAGES, value="JavaScript")
151
- target_code_output = gr.Code(label="Converted Code", language="javascript", lines=15, interactive=False)
152
 
153
- # Sync language highlighting with dropdowns
154
- source_lang_selection.change(lambda x: gr.update(language=x.lower()), inputs=source_lang_selection, outputs=source_code_input)
155
- target_lang_selection.change(lambda x: gr.update(language=x.lower()), inputs=target_lang_selection, outputs=target_code_output)
156
 
157
- # Convert button and action
158
- convert_button = gr.Button("Convert Code", variant="primary", scale=1)
159
  convert_button.click(
160
  fn=convert_code,
161
  inputs=[source_code_input, source_lang_selection, target_lang_selection, model_selection, openrouter_key],
@@ -163,10 +176,9 @@ with gr.Blocks(theme=NordTheme()) as app:
163
  api_name="convert"
164
  )
165
 
166
- # Footer
167
  gr.HTML(
168
  """<div style="text-align: center; margin-top: 24px; color: #a0aec0; font-size: 0.875rem;">
169
- <p>CodeVerter uses LLMs via OpenRouter. Results may require manual review.</p>
170
  </div>"""
171
  )
172
 
 
18
  font_mono=(fonts.GoogleFont("Fira Code"), "ui-monospace", "monospace"),
19
  )
20
  self.set(
 
21
  body_background_fill="#2E3440",
22
  body_text_color="#ECEFF4",
23
  block_background_fill="#3B4252",
 
25
  block_border_color="#4C566A",
26
  block_label_background_fill="#434C5E",
27
  block_label_text_color="#ECEFF4",
 
28
  input_background_fill="#434C5E",
29
  input_border_color="transparent",
 
 
 
30
  button_primary_background_fill="#5E81AC",
31
  button_primary_background_fill_hover="#81A1C1",
32
  button_primary_text_color="#ECEFF4",
33
  button_secondary_background_fill="#4C566A",
34
  button_secondary_background_fill_hover="#5a657a",
35
  button_secondary_text_color="#ECEFF4",
 
 
36
  border_color_accent="#5E81AC",
37
  background_fill_primary_dark="#2E3440",
38
  color_accent_soft="#4c566a",
 
 
 
 
 
39
  block_radius="12px",
40
  button_radius="8px",
41
  )
42
 
43
  # --- UI Configuration ---
44
 
45
+ # UPDATED: "Natural Language" is added to the list.
46
  LANGUAGES = [
47
+ 'Natural Language', 'Python', 'JavaScript', 'TypeScript', 'Java', 'C++', 'C#',
48
+ 'C', 'Go', 'Rust', 'Swift', 'Kotlin', 'PHP', 'Ruby', 'Scala', 'R', 'MATLAB',
49
  'Perl', 'Haskell', 'Lua', 'Dart', 'Elixir', 'F#', 'Clojure', 'SQL'
50
  ]
51
 
 
72
  def convert_code(
73
  source_code: str, source_lang: str, target_lang: str, model: str, api_key: str
74
  ):
75
+ """
76
+ Handles three conversion scenarios:
77
+ 1. Natural Language -> Code
78
+ 2. Code -> Natural Language
79
+ 3. Code -> Code
80
+ """
81
  if not source_code.strip():
82
+ raise gr.Error("Please enter some code or a description to convert.")
83
  if not api_key.strip():
84
  raise gr.Error("OpenRouter API key is required.")
85
  if not model or not model.strip():
86
  raise gr.Error("Please select or enter a model for the conversion.")
87
+
88
+ # Handle the edge case where both are "Natural Language"
89
+ if source_lang == "Natural Language" and target_lang == "Natural Language":
90
+ raise gr.Error("Please select a programming language for either the source or the target.")
91
 
92
  client = openai.OpenAI(base_url="https://openrouter.ai/api/v1", api_key=api_key)
93
+
94
+ # UPDATED: Logic to generate a prompt based on the conversion type
95
+ if source_lang == "Natural Language":
96
+ # Scenario 1: Natural Language -> Code
97
+ prompt = (
98
+ f"You are a programming expert. Based on the following description, write a complete and functional code snippet in {target_lang}. "
99
+ f"The user's request is: '{source_code}'.\n\n"
100
+ f"Your response must only contain the raw {target_lang} code without any explanations, comments, or markdown formatting (like ```)."
101
+ )
102
+ elif target_lang == "Natural Language":
103
+ # Scenario 2: Code -> Natural Language
104
+ prompt = (
105
+ f"You are a programming expert. Explain the following {source_lang} code in simple, natural English. "
106
+ f"Describe what the code does, its main logic, its inputs, and what it outputs. Do not include any code in your explanation.\n\n"
107
+ f"--- Start of {source_lang} Code ---\n"
108
+ f"{source_code}\n"
109
+ f"--- End of {source_lang} Code ---"
110
+ )
111
+ else:
112
+ # Scenario 3: Code -> Code (original logic)
113
+ prompt = (
114
+ f"You are an expert programmer. Convert the following {source_lang} code to {target_lang}. "
115
+ "Your response must only contain the raw, converted code. Do not include any explanations, comments, or markdown formatting (like ```)."
116
+ f"\n\n--- Start of {source_lang} Code ---\n"
117
+ f"{source_code}\n"
118
+ f"--- End of {source_lang} Code ---"
119
+ )
120
+
121
  try:
122
  completion = client.chat.completions.create(
123
  model=model,
 
132
 
133
  # --- Gradio User Interface ---
134
 
135
+ # Helper function to update Code component's language
136
+ def update_code_language(lang: str):
137
+ if lang == "Natural Language":
138
+ return gr.update(language="text", placeholder="Describe the code you want here...")
139
+ return gr.update(language=lang.lower(), placeholder=f"Enter your {lang} code here...")
140
+
141
  with gr.Blocks(theme=NordTheme()) as app:
142
  # Header
143
  gr.HTML(
144
  """
145
  <div style="display: flex; align-items: center; gap: 12px; padding: 10px;">
146
+ <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#81A1C1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m18 16 4-4-4-4"/><path d="m6 8-4 4 4 4"/><path d="m14.5 4-5 16"/></svg>
147
  <div>
148
  <h1 style="font-size: 1.5rem; font-weight: 700; color: #ECEFF4; margin: 0;">CodeVerter</h1>
149
+ <p style="font-size: 0.875rem; color: #D8DEE9; margin: 0;">Code & Natural Language Converter</p>
150
  </div>
151
  </div>
152
  """
153
  )
154
 
 
155
  with gr.Accordion("⚙️ Configuration", open=True):
156
+ openrouter_key = gr.Textbox(label="OpenRouter API Key", placeholder="Enter your OpenRouter API key...", type="password")
157
+ model_selection = gr.Dropdown(label="Select or Enter a Model Name", choices=MODELS, value=MODELS[0] if MODELS else None, allow_custom_value=True)
 
 
 
 
 
 
 
 
 
158
 
 
159
  with gr.Row(equal_height=False):
160
  with gr.Column(scale=1):
161
  source_lang_selection = gr.Dropdown(label="Source Language", choices=LANGUAGES, value="Python")
162
+ source_code_input = gr.Code(label="Source", language="python", value=DEFAULT_SOURCE_CODE, lines=15)
163
  with gr.Column(scale=1):
164
  target_lang_selection = gr.Dropdown(label="Target Language", choices=LANGUAGES, value="JavaScript")
165
+ target_code_output = gr.Code(label="Result", language="javascript", lines=15, interactive=False)
166
 
167
+ # UPDATED: Use a helper function for cleaner UI logic
168
+ source_lang_selection.change(fn=update_code_language, inputs=source_lang_selection, outputs=source_code_input)
169
+ target_lang_selection.change(lambda lang: gr.update(language=lang.lower() if lang != "Natural Language" else "text"), inputs=target_lang_selection, outputs=target_code_output)
170
 
171
+ convert_button = gr.Button("Convert", variant="primary", scale=1)
 
172
  convert_button.click(
173
  fn=convert_code,
174
  inputs=[source_code_input, source_lang_selection, target_lang_selection, model_selection, openrouter_key],
 
176
  api_name="convert"
177
  )
178
 
 
179
  gr.HTML(
180
  """<div style="text-align: center; margin-top: 24px; color: #a0aec0; font-size: 0.875rem;">
181
+ <p>Powered by OpenRouter. Results may require manual review.</p>
182
  </div>"""
183
  )
184