CoolFace
Apppublic

shukdevdatta123/Competitive-Programming-Assistant

sourceHugging Facemitupdated 1y agoView on Hugging Face
1likes
app.py175 linesDownload Raw Back to root
1import gradio as gr2import os3from openai import OpenAI4import time5 6def solve_competitive_problem(problem_statement, language_choice, api_key, progress=gr.Progress()):7    """8    Generate a solution for a competitive programming problem9    10    Args:11        problem_statement (str): The problem statement12        language_choice (str): Programming language for the solution13        api_key (str): OpenRouter API key14        progress: Gradio progress tracker15    16    Returns:17        str: Step-by-step solution with code18    """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        progress(0.1, "Initializing...")27        28        # Initialize OpenAI client with OpenRouter base URL29        client = OpenAI(30            base_url="https://openrouter.ai/api/v1",31            api_key=api_key,32        )33        34        progress(0.3, "Creating prompt...")35        36        # Create a more detailed prompt with language preference37        prompt = f"""38You are an expert competitive programmer. Analyze the following problem and provide a step-by-step solution with explanations and code in {language_choice}.39Problem:40{problem_statement}41Your response should include:421. Problem Analysis:43   - Clear restatement of the problem in your own words44   - Identification of input/output formats45   - Key constraints and edge cases to consider46   - Time and space complexity requirements472. Approach:48   - High-level strategy to solve the problem49   - Why this approach is optimal compared to alternatives50   - Any mathematical insights or observations51   - Data structures that will be helpful523. Algorithm:53   - Detailed step-by-step breakdown of the algorithm54   - Clear explanation of the logic behind each step55   - Time complexity analysis with justification56   - Space complexity analysis with justification57   - Any optimizations made to improve performance584. Implementation:59   - Clean, efficient, and well-commented {language_choice} code60   - Proper variable naming and code organization61   - Error handling and edge case management62   - Optimized for both readability and performance635. Testing:64   - Example test cases with expected outputs65   - Edge case testing scenarios66   - Explanation of how to verify correctness67   - Potential areas where the solution might need improvement68Format your answer with clear headings and subheadings. Use markdown formatting for better readability.69        """70        71        progress(0.5, "Generating solution...")72        73        # Call the model74        completion = client.chat.completions.create(75            extra_headers={76                "HTTP-Referer": "https://competitive-programming-assistant.app",77                "X-Title": "Competitive Programming Assistant",78            },79            model="open-r1/olympiccoder-7b:free",80            messages=[81                {82                    "role": "user",83                    "content": prompt84                }85            ],86            temperature=0.7,87            stream=False88        )89        90        progress(0.9, "Processing response...")91        92        solution = completion.choices[0].message.content93        94        progress(1.0, "Complete!")95        return solution96        97    except Exception as e:98        return f"Error: {str(e)}"99 100# Create a Gradio interface101with gr.Blocks(title="Competitive Programming Assistant", theme=gr.themes.Soft()) as app:102    gr.Markdown("""103    # ๐Ÿ† Competitive Programming Assistant104    105    Upload a problem statement from Codeforces, LeetCode, or any competitive programming platform to get:106    - Step-by-step analysis107    - Optimal solution approach108    - Complete code implementation109    - Time and space complexity analysis110    111    Powered by the OlympicCoder model.112    """)113    114    with gr.Row():115        with gr.Column(scale=2):116            api_key_input = gr.Textbox(117                placeholder="Enter your OpenRouter API key here",118                label="OpenRouter API Key",119                type="password"120            )121            122            problem_input = gr.Textbox(123                placeholder="Paste your competitive programming problem statement here...",124                label="Problem Statement",125                lines=10126            )127            128            language = gr.Dropdown(129                choices=["Python", "C++", "Java", "JavaScript"],130                value="Python",131                label="Programming Language"132            )133            134            submit_btn = gr.Button("Generate Solution", variant="primary")135        136        with gr.Column(scale=3):137            solution_output = gr.Markdown(138                label="Generated Solution"139            )140    141    with gr.Accordion("About", open=False):142        gr.Markdown("""143        ### How to use this app:144        145        1. Enter your OpenRouter API key (get one at [openrouter.ai](https://openrouter.ai))146        2. Paste the complete problem statement147        3. Select your preferred programming language148        4. Click "Generate Solution"149        150        ### Tips for best results:151        152        - Include the entire problem, including input/output formats and constraints153        - Make sure to include example inputs and outputs154        - For complex problems, consider adding clarifying notes155        156        ### Solution Format:157        158        Your solution will include:159        1. **Problem Analysis** - Breaking down the problem into manageable components160        2. **Approach** - Strategic methodology with mathematical insights161        3. **Algorithm** - Detailed step-by-step procedure with complexity analysis162        4. **Implementation** - Clean, commented code in your chosen language163        5. **Testing** - Example test cases and verification methods164        """)165    166    # Handle form submission167    submit_btn.click(168        solve_competitive_problem,169        inputs=[problem_input, language, api_key_input],170        outputs=solution_output171    )172 173# Launch the app174if __name__ == "__main__":175    app.launch()