shukdevdatta123 commited on
Commit
5e1d6fb
·
verified ·
1 Parent(s): 22c1c37

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +153 -47
app.py CHANGED
@@ -1,16 +1,57 @@
1
  import gradio as gr
2
- from openai import OpenAI
3
 
4
- def generate_solution(api_key, problem_statement):
5
- # Check if inputs are provided
6
- if not api_key or not problem_statement:
7
- return "Please provide both an API key and a problem statement."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
 
 
 
 
 
 
 
9
  try:
10
  client = OpenAI(
11
  base_url="https://openrouter.ai/api/v1",
12
  api_key=api_key.strip(),
13
  )
 
 
14
  completion = client.chat.completions.create(
15
  model="open-r1/olympiccoder-7b:free",
16
  messages=[
@@ -26,60 +67,98 @@ def generate_solution(api_key, problem_statement):
26
  temperature=0.3,
27
  max_tokens=2048
28
  )
 
 
29
  response = completion.choices[0].message.content
30
- return format_response(response)
 
 
 
 
 
31
 
32
  except Exception as e:
33
- return f"Error: {str(e)}"
 
 
34
 
35
  def format_response(response):
 
 
 
 
36
  formatted = []
 
 
 
37
  in_code = False
38
- code_buffer = []
39
- explanation_buffer = []
40
 
41
- for line in response.split('\n'):
42
  if line.strip().startswith('```'):
43
- if in_code and code_buffer:
44
- # Skip language marker if present
45
- if len(code_buffer) > 0 and any(code_buffer[0].strip().lower() == lang for lang in ["python", "java", "c++", "cpp"]):
46
- code_content = '\n'.join(code_buffer[1:])
47
- else:
48
- code_content = '\n'.join(code_buffer)
49
- formatted.append(f"```python\n{code_content}\n```")
50
- code_buffer = []
51
  in_code = not in_code
52
  continue
53
-
54
  if in_code:
55
- code_buffer.append(line)
56
- else:
57
- explanation_buffer.append(line)
58
 
59
- # Handle case where code block wasn't properly closed
60
- if in_code and code_buffer:
61
- if len(code_buffer) > 0 and any(code_buffer[0].strip().lower() == lang for lang in ["python", "java", "c++", "cpp"]):
62
- code_content = '\n'.join(code_buffer[1:])
63
- else:
64
- code_content = '\n'.join(code_buffer)
65
- formatted.append(f"```python\n{code_content}\n```")
66
 
67
- if explanation_buffer:
68
- formatted.append("### Explanation\n" + '\n'.join(explanation_buffer))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
- return "\n\n".join(formatted)
 
 
 
 
71
 
72
- with gr.Blocks(title="Competitive Programming Assistant") as app:
 
73
  gr.Markdown("# 🏆 Competitive Programming Assistant")
74
  gr.Markdown("Powered by OlympicCoder-7B via OpenRouter AI")
75
 
76
  with gr.Row():
77
- api_key = gr.Textbox(
78
- label="OpenRouter API Key",
79
- type="password",
80
- placeholder="Enter your API key here...",
81
- value="" # Set default value to empty string
82
- )
 
 
 
 
 
 
 
 
 
 
83
 
84
  with gr.Row():
85
  problem_input = gr.Textbox(
@@ -88,16 +167,15 @@ with gr.Blocks(title="Competitive Programming Assistant") as app:
88
  placeholder="Paste your programming problem here..."
89
  )
90
 
91
- submit_btn = gr.Button("Generate Solution", variant="primary")
92
 
93
- output = gr.Markdown(label="Solution")
 
94
 
95
- submit_btn.click(
96
- fn=generate_solution,
97
- inputs=[api_key, problem_input],
98
- outputs=output
99
- )
100
 
 
101
  gr.Examples(
102
  examples=[
103
  [
@@ -109,6 +187,34 @@ with gr.Blocks(title="Competitive Programming Assistant") as app:
109
  ],
110
  inputs=[problem_input]
111
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
  if __name__ == "__main__":
114
- app.launch(server_port=7860, share=True) # Changed share to True to make it accessible externally
 
 
 
 
 
1
  import gradio as gr
2
+ import time
3
 
4
+ # Try importing OpenAI with error handling
5
+ try:
6
+ from openai import OpenAI
7
+ except ImportError:
8
+ print("OpenAI package not installed. Installing now...")
9
+ import subprocess
10
+ import sys
11
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "openai"])
12
+ from openai import OpenAI
13
+
14
+ def test_api_connection(api_key):
15
+ """Test the API connection and return a status message"""
16
+ if not api_key or api_key.strip() == "":
17
+ return False, "API key is required"
18
+
19
+ try:
20
+ client = OpenAI(
21
+ base_url="https://openrouter.ai/api/v1",
22
+ api_key=api_key.strip(),
23
+ )
24
+ # Simple request to test connection
25
+ client.models.list()
26
+ return True, "API connection successful"
27
+ except Exception as e:
28
+ return False, f"API connection failed: {str(e)}"
29
+
30
+ def generate_solution(api_key, problem_statement, progress=gr.Progress()):
31
+ """Generate solution with progress updates"""
32
+ progress(0, desc="Starting...")
33
+
34
+ # Input validation
35
+ if not api_key or api_key.strip() == "":
36
+ return "Error: OpenRouter API key is required"
37
+
38
+ if not problem_statement or problem_statement.strip() == "":
39
+ return "Error: Please provide a problem statement"
40
 
41
+ progress(0.1, desc="Validating API key...")
42
+ # Test API connection first
43
+ success, message = test_api_connection(api_key)
44
+ if not success:
45
+ return f"Error: {message}"
46
+
47
+ progress(0.3, desc="Sending request to AI model...")
48
  try:
49
  client = OpenAI(
50
  base_url="https://openrouter.ai/api/v1",
51
  api_key=api_key.strip(),
52
  )
53
+
54
+ progress(0.5, desc="Generating solution...")
55
  completion = client.chat.completions.create(
56
  model="open-r1/olympiccoder-7b:free",
57
  messages=[
 
67
  temperature=0.3,
68
  max_tokens=2048
69
  )
70
+
71
+ progress(0.8, desc="Processing response...")
72
  response = completion.choices[0].message.content
73
+
74
+ progress(0.9, desc="Formatting output...")
75
+ formatted_response = format_response(response)
76
+
77
+ progress(1.0, desc="Done!")
78
+ return formatted_response
79
 
80
  except Exception as e:
81
+ error_message = str(e)
82
+ print(f"Error occurred: {error_message}")
83
+ return f"Error: {error_message}"
84
 
85
  def format_response(response):
86
+ """Format the AI response into markdown with code blocks"""
87
+ if not response:
88
+ return "Error: Received empty response from AI model"
89
+
90
  formatted = []
91
+ lines = response.split('\n')
92
+
93
+ # Find code blocks
94
  in_code = False
95
+ code_blocks = []
96
+ current_block = []
97
 
98
+ for line in lines:
99
  if line.strip().startswith('```'):
100
+ if in_code:
101
+ code_blocks.append(current_block)
102
+ current_block = []
103
+ else:
104
+ current_block = []
 
 
 
105
  in_code = not in_code
106
  continue
107
+
108
  if in_code:
109
+ current_block.append(line)
 
 
110
 
111
+ # Handle unclosed code block
112
+ if in_code and current_block:
113
+ code_blocks.append(current_block)
 
 
 
 
114
 
115
+ # Process code blocks and explanations
116
+ processed_response = response
117
+
118
+ # Replace each code block with properly formatted markdown
119
+ for i, block in enumerate(code_blocks):
120
+ # Skip language identifier if present
121
+ if block and any(block[0].strip().lower() == lang for lang in ["python", "java", "c++", "cpp", "javascript"]):
122
+ code_content = '\n'.join(block[1:])
123
+ lang = block[0].strip().lower()
124
+ else:
125
+ code_content = '\n'.join(block)
126
+ lang = "python" # Default to Python
127
+
128
+ # Create search pattern for the original block
129
+ if i < len(code_blocks) - 1 or not in_code:
130
+ block_text = '```' + '\n' + '\n'.join(block) + '\n' + '```'
131
+ else:
132
+ block_text = '```' + '\n' + '\n'.join(block)
133
 
134
+ # Replace with properly formatted block
135
+ formatted_block = f"```{lang}\n{code_content}\n```"
136
+ processed_response = processed_response.replace(block_text, formatted_block)
137
+
138
+ return processed_response
139
 
140
+ # Define the Gradio interface
141
+ with gr.Blocks(title="Competitive Programming Assistant", theme=gr.themes.Soft()) as app:
142
  gr.Markdown("# 🏆 Competitive Programming Assistant")
143
  gr.Markdown("Powered by OlympicCoder-7B via OpenRouter AI")
144
 
145
  with gr.Row():
146
+ with gr.Column():
147
+ api_key = gr.Textbox(
148
+ label="OpenRouter API Key",
149
+ type="password",
150
+ placeholder="Enter your API key here...",
151
+ value=""
152
+ )
153
+
154
+ test_btn = gr.Button("Test API Connection", variant="secondary")
155
+ api_status = gr.Textbox(label="API Status", interactive=False)
156
+
157
+ test_btn.click(
158
+ fn=test_api_connection,
159
+ inputs=[api_key],
160
+ outputs=[gr.Checkbox(visible=False), api_status]
161
+ )
162
 
163
  with gr.Row():
164
  problem_input = gr.Textbox(
 
167
  placeholder="Paste your programming problem here..."
168
  )
169
 
170
+ submit_btn = gr.Button("Generate Solution", variant="primary", size="lg")
171
 
172
+ # Add a status indicator
173
+ status = gr.Markdown("Ready to generate solutions")
174
 
175
+ # Output area
176
+ solution_output = gr.Markdown(label="Solution")
 
 
 
177
 
178
+ # Example problems
179
  gr.Examples(
180
  examples=[
181
  [
 
187
  ],
188
  inputs=[problem_input]
189
  )
190
+
191
+ # Set up event handlers with additional status updates
192
+ def on_submit_click(api_key, problem):
193
+ return "Generating solution... Please wait."
194
+
195
+ submit_btn.click(
196
+ fn=on_submit_click,
197
+ inputs=[api_key, problem_input],
198
+ outputs=[status],
199
+ queue=False
200
+ ).then(
201
+ fn=generate_solution,
202
+ inputs=[api_key, problem_input],
203
+ outputs=[solution_output],
204
+ queue=True
205
+ ).success(
206
+ fn=lambda: "Solution generated successfully!",
207
+ inputs=None,
208
+ outputs=[status]
209
+ ).error(
210
+ fn=lambda: "An error occurred. Please check your inputs and try again.",
211
+ inputs=None,
212
+ outputs=[status]
213
+ )
214
 
215
  if __name__ == "__main__":
216
+ try:
217
+ print("Starting Competitive Programming Assistant...")
218
+ app.launch(server_port=7860, share=True, debug=True)
219
+ except Exception as e:
220
+ print(f"Error launching app: {str(e)}")