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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -116
app.py CHANGED
@@ -1,31 +1,75 @@
1
  import gradio as gr
2
  import openai
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
  # --- UI Configuration ---
5
 
6
- # Extracted from the provided React code
7
  LANGUAGES = [
8
  'Python', 'JavaScript', 'TypeScript', 'Java', 'C++', 'C#', 'C', 'Go',
9
  'Rust', 'Swift', 'Kotlin', 'PHP', 'Ruby', 'Scala', 'R', 'MATLAB',
10
- 'Perl', 'Haskell', 'Lua', 'Dart', 'Elixir', 'F#', 'Clojure',
11
- 'Objective-C', 'Visual Basic', 'Bash', 'PowerShell', 'SQL', 'HTML',
12
- 'CSS', 'JSON', 'XML', 'YAML', 'Assembly', 'Fortran', 'COBOL',
13
- 'Pascal', 'Delphi', 'Groovy', 'Julia', 'Nim', 'Crystal', 'Zig',
14
- 'V', 'OCaml', 'Erlang', 'Prolog', 'Lisp', 'Scheme', 'Racket'
15
  ]
16
 
17
- # A selection of popular and capable models available via OpenRouter
18
- # You can expand this list with other models from openrouter.ai
19
- MODELS = [
20
- "anthropic/claude-3.5-sonnet",
21
- "google/gemini-flash-1.5",
22
- "meta-llama/llama-3-8b-instruct",
23
- "mistralai/mistral-large",
24
- "openai/gpt-4o",
25
- "microsoft/wizardlm-2-8x22b",
26
- ]
27
 
28
- # Default example code from the original application
29
  DEFAULT_SOURCE_CODE = """# Example Python code
30
  def fibonacci(n):
31
  if n <= 1:
@@ -37,29 +81,16 @@ print(fibonacci(10))"""
37
  # --- Core Conversion Logic ---
38
 
39
  def convert_code(
40
- source_code: str,
41
- source_lang: str,
42
- target_lang: str,
43
- model: str,
44
- api_key: str,
45
  ):
46
- """
47
- Uses an LLM via OpenRouter to convert code from one language to another.
48
- """
49
  if not source_code.strip():
50
  raise gr.Error("Please enter some code to convert.")
51
  if not api_key.strip():
52
  raise gr.Error("OpenRouter API key is required.")
53
- if not model:
54
- raise gr.Error("Please select a model for the conversion.")
55
 
56
- # Initialize the OpenAI client to point to OpenRouter's API
57
- client = openai.OpenAI(
58
- base_url="https://openrouter.ai/api/v1",
59
- api_key=api_key,
60
- )
61
-
62
- # Construct the prompt for the LLM
63
  prompt = (
64
  f"You are an expert programmer. Convert the following {source_lang} code "
65
  f"to {target_lang}. Your response should only contain the raw, converted code. "
@@ -68,124 +99,75 @@ def convert_code(
68
  f"{source_code}\n"
69
  f"--- End of {source_lang} Code ---"
70
  )
71
-
72
  try:
73
- # Make the API call to the selected model
74
  completion = client.chat.completions.create(
75
  model=model,
76
- messages=[
77
- {"role": "user", "content": prompt},
78
- ],
79
- temperature=0.1, # Lower temperature for more deterministic output
80
- max_tokens=2048,
81
  )
82
- converted_code = completion.choices[0].message.content.strip()
83
- return converted_code
84
-
85
  except openai.AuthenticationError:
86
- raise gr.Error("Authentication failed. Please check your OpenRouter API key.")
87
  except Exception as e:
88
- # A catch-all for other potential API or network errors
89
- raise gr.Error(f"An error occurred during conversion: {e}")
90
 
91
  # --- Gradio User Interface ---
92
 
93
- with gr.Blocks(
94
- theme=gr.themes.Monochrome(),
95
- css=".gradio-container {background-color: #0f172a}" # Dark theme like the original
96
- ) as app:
97
  # Header
98
- with gr.Row():
99
- gr.HTML(
100
- """
101
- <div style="display: flex; align-items: center; gap: 12px; padding: 10px;">
102
- <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="#3b82f6" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-code-xml"><path d="m18 16 4-4-4-4"/><path d="m6 8-4 4 4 4"/><path d="m14.5 4-5 16"/></svg>
103
- <div>
104
- <h1 style="font-size: 1.5rem; font-weight: 700; color: #ffffff; margin: 0;">CodeVerter</h1>
105
- <p style="font-size: 0.875rem; color: #9ca3af; margin: 0;">Programming Language Converter via OpenRouter</p>
106
- </div>
107
  </div>
108
- """
109
- )
 
110
 
111
- # API Key and Model Selection
112
  with gr.Accordion("⚙️ Configuration", open=True):
113
  openrouter_key = gr.Textbox(
114
  label="OpenRouter API Key",
115
- placeholder="Enter your OpenRouter API key here...",
116
  type="password",
117
- elem_id="api-key-textbox",
118
  )
119
  model_selection = gr.Dropdown(
120
- label="Select LLM Model",
121
  choices=MODELS,
122
- value=MODELS[0], # Default to the first model in the list
 
123
  )
124
 
125
  # Main conversion interface
126
  with gr.Row(equal_height=False):
127
- # Input column
128
  with gr.Column(scale=1):
129
- source_lang_selection = gr.Dropdown(
130
- label="Source Language",
131
- choices=LANGUAGES,
132
- value="Python",
133
- )
134
- source_code_input = gr.Code(
135
- label="Source Code",
136
- language="python", # Start with python syntax highlighting
137
- value=DEFAULT_SOURCE_CODE,
138
- lines=15,
139
- )
140
-
141
- # Output column
142
  with gr.Column(scale=1):
143
- target_lang_selection = gr.Dropdown(
144
- label="Target Language",
145
- choices=LANGUAGES,
146
- value="JavaScript",
147
- )
148
- target_code_output = gr.Code(
149
- label="Converted Code",
150
- language="javascript", # Start with javascript syntax highlighting
151
- lines=15,
152
- interactive=False, # Make it read-only
153
- )
154
 
155
- # Keep language highlighting in sync with dropdowns
156
- source_lang_selection.change(
157
- lambda x: gr.update(language=x.lower()),
158
- inputs=source_lang_selection,
159
- outputs=source_code_input
160
- )
161
- target_lang_selection.change(
162
- lambda x: gr.update(language=x.lower()),
163
- inputs=target_lang_selection,
164
- outputs=target_code_output
165
- )
166
 
167
  # Convert button and action
168
- convert_button = gr.Button("Convert Code", variant="primary")
169
  convert_button.click(
170
  fn=convert_code,
171
- inputs=[
172
- source_code_input,
173
- source_lang_selection,
174
- target_lang_selection,
175
- model_selection,
176
- openrouter_key,
177
- ],
178
  outputs=target_code_output,
179
  api_name="convert"
180
  )
181
 
182
  # Footer
183
  gr.HTML(
184
- """
185
- <div style="text-align: center; margin-top: 24px; color: #9ca3af; font-size: 0.875rem;">
186
- <p>CodeVerter uses LLMs via OpenRouter to convert code. Results may require manual review.</p>
187
- </div>
188
- """
189
  )
190
 
191
  if __name__ == "__main__":
 
1
  import gradio as gr
2
  import openai
3
+ from gradio.themes.base import Base
4
+ from gradio.themes.utils import colors, fonts, sizes
5
+
6
+ # --- Custom Theme Definition ---
7
+
8
+ class NordTheme(Base):
9
+ """
10
+ A custom Gradio theme inspired by the Nord color palette.
11
+ """
12
+ def __init__(self):
13
+ super().__init__(
14
+ primary_hue=colors.blue,
15
+ secondary_hue=colors.sky,
16
+ neutral_hue=colors.slate,
17
+ font=(fonts.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"),
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",
25
+ block_border_width="1px",
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
 
63
+ MODELS = sorted([
64
+ "agentica-org/deepcoder-14b-preview:free", "deepseek/deepseek-chat-v3:free",
65
+ "deepseek/deepseek-r1-0528:free", "google/gemma-3-27b-it:free",
66
+ "google/gemini-2.0-flash-exp:free", "meta-llama/llama-3.3-70b-instruct:free",
67
+ "mistralai/devstral-small-2505:free", "mistralai/mistral-small-3.2-24b-instruct-2506:free",
68
+ "moonshotai/kimi-dev-72b:free", "openrouter/cypher-alpha:free",
69
+ "qwen/qwen-2.5-coder-32b-instruct:free", "qwen/qwen3-235b-a22b-04-28:free",
70
+ "qwen/qwq-32b:free",
71
+ ])
 
72
 
 
73
  DEFAULT_SOURCE_CODE = """# Example Python code
74
  def fibonacci(n):
75
  if n <= 1:
 
81
  # --- Core Conversion Logic ---
82
 
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. "
 
99
  f"{source_code}\n"
100
  f"--- End of {source_lang} Code ---"
101
  )
 
102
  try:
 
103
  completion = client.chat.completions.create(
104
  model=model,
105
+ messages=[{"role": "user", "content": prompt}],
106
+ temperature=0.1, max_tokens=2048
 
 
 
107
  )
108
+ return completion.choices[0].message.content.strip()
 
 
109
  except openai.AuthenticationError:
110
+ raise gr.Error("Authentication failed. Check your OpenRouter API key.")
111
  except Exception as e:
112
+ raise gr.Error(f"An error occurred: {e}")
 
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],
 
 
 
 
 
 
162
  outputs=target_code_output,
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
 
173
  if __name__ == "__main__":