Update app.py
Browse files
app.py
CHANGED
|
@@ -1,220 +1,136 @@
|
|
| 1 |
import gradio as gr
|
|
|
|
|
|
|
| 2 |
import time
|
|
|
|
| 3 |
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 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 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 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 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
-
|
| 42 |
-
|
| 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
|
| 52 |
)
|
| 53 |
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
completion = client.chat.completions.create(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
model="open-r1/olympiccoder-7b:free",
|
| 57 |
messages=[
|
| 58 |
-
{
|
| 59 |
-
"role": "system",
|
| 60 |
-
"content": "You are a competitive programming expert. Provide a correct solution with clear reasoning. First output the code, then explain the approach."
|
| 61 |
-
},
|
| 62 |
{
|
| 63 |
"role": "user",
|
| 64 |
-
"content":
|
| 65 |
}
|
| 66 |
],
|
| 67 |
-
temperature=0.
|
| 68 |
-
|
| 69 |
)
|
| 70 |
|
| 71 |
-
|
| 72 |
-
|
| 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 |
-
|
| 82 |
-
print(f"Error occurred: {error_message}")
|
| 83 |
-
return f"Error: {error_message}"
|
| 84 |
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 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 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
| 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 |
-
|
|
|
|
| 148 |
label="OpenRouter API Key",
|
| 149 |
-
type="password"
|
| 150 |
-
placeholder="Enter your API key here...",
|
| 151 |
-
value=""
|
| 152 |
)
|
| 153 |
|
| 154 |
-
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
| 156 |
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
)
|
| 162 |
|
| 163 |
-
with gr.
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
# Example problems
|
| 179 |
-
gr.Examples(
|
| 180 |
-
examples=[
|
| 181 |
-
[
|
| 182 |
-
"Given an array of integers, find two numbers such that they add up to a specific target number."
|
| 183 |
-
],
|
| 184 |
-
[
|
| 185 |
-
"Implement a function to calculate the minimum number of operations required to transform one string into another using only insertion, deletion, and substitution."
|
| 186 |
-
]
|
| 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 |
-
|
| 197 |
-
inputs=[
|
| 198 |
-
outputs=
|
| 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 |
-
|
| 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)}")
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
from openai import OpenAI
|
| 4 |
import time
|
| 5 |
+
import markdown
|
| 6 |
|
| 7 |
+
def solve_competitive_problem(problem_statement, language_choice, api_key):
|
| 8 |
+
"""
|
| 9 |
+
Generate a solution for a competitive programming problem
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
+
Args:
|
| 12 |
+
problem_statement (str): The problem statement
|
| 13 |
+
language_choice (str): Programming language for the solution
|
| 14 |
+
api_key (str): OpenRouter API key
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
+
Returns:
|
| 17 |
+
str: Step-by-step solution with code
|
| 18 |
+
"""
|
| 19 |
+
if not api_key.strip():
|
| 20 |
+
return "Error: Please provide your OpenRouter API key."
|
| 21 |
|
| 22 |
+
if not problem_statement.strip():
|
| 23 |
+
return "Error: Please provide a problem statement."
|
|
|
|
|
|
|
|
|
|
| 24 |
|
|
|
|
| 25 |
try:
|
| 26 |
+
# Initialize OpenAI client with OpenRouter base URL
|
| 27 |
client = OpenAI(
|
| 28 |
base_url="https://openrouter.ai/api/v1",
|
| 29 |
+
api_key=api_key,
|
| 30 |
)
|
| 31 |
|
| 32 |
+
# Create prompt with language preference
|
| 33 |
+
prompt = f"""
|
| 34 |
+
You are an expert competitive programmer. Analyze the following problem and provide a step-by-step solution with explanations and code in {language_choice}.
|
| 35 |
+
|
| 36 |
+
Problem:
|
| 37 |
+
{problem_statement}
|
| 38 |
+
|
| 39 |
+
Your response should include:
|
| 40 |
+
1. Problem Analysis: Break down the problem statement and identify the key challenges
|
| 41 |
+
2. Approach: Describe your approach to solve the problem and why it's optimal
|
| 42 |
+
3. Algorithm: Explain the algorithm you'll use with time and space complexity analysis
|
| 43 |
+
4. Implementation: Write clean, efficient, and well-commented {language_choice} code
|
| 44 |
+
5. Testing: Explain how to test the solution with example inputs/outputs
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
# Call the model
|
| 48 |
completion = client.chat.completions.create(
|
| 49 |
+
extra_headers={
|
| 50 |
+
"HTTP-Referer": "https://competitive-programming-assistant.app",
|
| 51 |
+
"X-Title": "Competitive Programming Assistant",
|
| 52 |
+
},
|
| 53 |
model="open-r1/olympiccoder-7b:free",
|
| 54 |
messages=[
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
{
|
| 56 |
"role": "user",
|
| 57 |
+
"content": prompt
|
| 58 |
}
|
| 59 |
],
|
| 60 |
+
temperature=0.7,
|
| 61 |
+
stream=False
|
| 62 |
)
|
| 63 |
|
| 64 |
+
solution = completion.choices[0].message.content
|
| 65 |
+
return solution
|
|
|
|
|
|
|
|
|
|
| 66 |
|
|
|
|
|
|
|
|
|
|
| 67 |
except Exception as e:
|
| 68 |
+
return f"Error: {str(e)}"
|
|
|
|
|
|
|
| 69 |
|
| 70 |
+
# Create a Gradio interface
|
| 71 |
+
with gr.Blocks(title="Competitive Programming Assistant", theme=gr.themes.Soft()) as app:
|
| 72 |
+
gr.Markdown("""
|
| 73 |
+
# 🏆 Competitive Programming Assistant
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
+
Upload a problem statement from Codeforces, LeetCode, or any competitive programming platform to get:
|
| 76 |
+
- Step-by-step analysis
|
| 77 |
+
- Optimal solution approach
|
| 78 |
+
- Complete code implementation
|
| 79 |
+
- Time and space complexity analysis
|
| 80 |
|
| 81 |
+
Powered by the OlympicCoder model.
|
| 82 |
+
""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
with gr.Row():
|
| 85 |
+
with gr.Column(scale=2):
|
| 86 |
+
api_key_input = gr.Textbox(
|
| 87 |
+
placeholder="Enter your OpenRouter API key here",
|
| 88 |
label="OpenRouter API Key",
|
| 89 |
+
type="password"
|
|
|
|
|
|
|
| 90 |
)
|
| 91 |
|
| 92 |
+
problem_input = gr.Textbox(
|
| 93 |
+
placeholder="Paste your competitive programming problem statement here...",
|
| 94 |
+
label="Problem Statement",
|
| 95 |
+
lines=10
|
| 96 |
+
)
|
| 97 |
|
| 98 |
+
language = gr.Dropdown(
|
| 99 |
+
choices=["Python", "C++", "Java", "JavaScript"],
|
| 100 |
+
value="Python",
|
| 101 |
+
label="Programming Language"
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
submit_btn = gr.Button("Generate Solution", variant="primary")
|
| 105 |
+
|
| 106 |
+
with gr.Column(scale=3):
|
| 107 |
+
solution_output = gr.Markdown(
|
| 108 |
+
label="Generated Solution"
|
| 109 |
)
|
| 110 |
|
| 111 |
+
with gr.Accordion("About", open=False):
|
| 112 |
+
gr.Markdown("""
|
| 113 |
+
### How to use this app:
|
| 114 |
+
|
| 115 |
+
1. Enter your OpenRouter API key (get one at [openrouter.ai](https://openrouter.ai))
|
| 116 |
+
2. Paste the complete problem statement
|
| 117 |
+
3. Select your preferred programming language
|
| 118 |
+
4. Click "Generate Solution"
|
| 119 |
+
|
| 120 |
+
### Tips for best results:
|
| 121 |
+
|
| 122 |
+
- Include the entire problem, including input/output formats and constraints
|
| 123 |
+
- Make sure to include example inputs and outputs
|
| 124 |
+
- For complex problems, consider adding clarifying notes
|
| 125 |
+
""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
+
# Handle form submission
|
| 128 |
submit_btn.click(
|
| 129 |
+
solve_competitive_problem,
|
| 130 |
+
inputs=[problem_input, language, api_key_input],
|
| 131 |
+
outputs=solution_output
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
)
|
| 133 |
|
| 134 |
+
# Launch the app
|
| 135 |
if __name__ == "__main__":
|
| 136 |
+
app.launch()
|
|
|
|
|
|
|
|
|
|
|
|