File size: 4,247 Bytes
cef8a01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import os
import gradio as gr
import tempfile
import zipfile
from groq import Groq
from dotenv import load_dotenv
from .generator import AIReadmeGenerator

# Validate the API key using the provided format
def validate_api_key(api_key):
    """
    Validate the API key using a test completion request.
    """
    try:
        client = Groq(api_key=api_key)
        response = client.chat.completions.create(
            model="llama-3.1-8b-instant",
            messages=[
                {"role": "system", "content": "Validation test for API key."},
                {"role": "user", "content": "Hello, world!"}
            ],
            temperature=0.1,
            max_tokens=5,
        )
        if response and response.choices:
            return True, "API key is valid!"
        else:
            return False, "API key validation failed: Empty response."
    except Exception as e:
        return False, f"Invalid API key. Error: {str(e)}"

# Generate README
def generate_readme_with_key(project_folder, api_key):
    """
    Generate the README for a given project folder using the provided API key.
    """
    try:
        # Use the API key dynamically
        generator = AIReadmeGenerator(api_key)
        with tempfile.TemporaryDirectory() as temp_dir:
            # Extract uploaded ZIP file
            with zipfile.ZipFile(project_folder, 'r') as zip_ref:
                zip_ref.extractall(temp_dir)
            
            # Generate the README
            readme_content = generator.generate_concise_readme(temp_dir)
            
            return readme_content, readme_content
    except zipfile.BadZipFile:
        return "Error: Uploaded file is not a valid ZIP archive.", "Error: Invalid ZIP archive."
    except Exception as e:
        return f"Error generating README: {str(e)}", f"Error generating README: {str(e)}"

# Handle user login
def on_login(api_key):
    is_valid, message = validate_api_key(api_key)
    if is_valid:
        return gr.update(visible=False), gr.update(visible=True), gr.Markdown(f"**Success!** {message}", visible=True)
    else:
        return gr.update(visible=True), gr.update(visible=False), gr.Markdown(f"**Error!** {message}", visible=True)

# Create Gradio UI
def create_ui():
    with gr.Blocks(title="AI README Generator") as demo:
        # Login Section
        with gr.Column(visible=True) as login_section:
            gr.Markdown("## Login to Access the AI README Generator")
            api_key_input = gr.Textbox(label="Enter your API Key:", type="password")
            login_button = gr.Button("Login")
            login_feedback = gr.Markdown(visible=False)

            gr.Markdown("""
            ### Login Instructions
            1. **Sign Up / Log In** at [Groq API Portal](https://console.groq.com/keys).
            2. **Generate an API Key** in the API Keys section.
            3. **Copy and Paste the API Key** into the box above.
            4. **Click Login** to proceed.
            """)

        # README Generator Section
        with gr.Column(visible=False) as readme_section:
            gr.Markdown("# AI README Craft")
            gr.Markdown("""
            ## Instructions
            - **Step 1:** Convert your project folder into a ZIP file.
            - **Step 2:** Upload the ZIP file using the form below.
            - **Step 3:** Click the **Generate README** button.
            - **Note:** Larger files may take more time to process. Please be patient!
            """)
            folder_input = gr.File(file_count="single", type="filepath", label="📂 Upload Your Project (ZIP)")
            generate_btn = gr.Button("✨ Generate README")
            with gr.Row():
                readme_output = gr.Textbox(lines=20, interactive=False, label="Generated README")
                readme_markdown = gr.Markdown(label="README Preview")
        
        # Button Click Events
        login_button.click(
            on_login,
            inputs=[api_key_input],
            outputs=[login_section, readme_section, login_feedback]
        )
        generate_btn.click(
            generate_readme_with_key,
            inputs=[folder_input, api_key_input],
            outputs=[readme_output, readme_markdown]
        )

    return demo