gr8monk3ys commited on
Commit
12e48fa
·
verified ·
1 Parent(s): 6ff59d0

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. README.md +67 -5
  2. app.py +226 -0
  3. requirements.txt +3 -0
README.md CHANGED
@@ -1,12 +1,74 @@
1
  ---
2
  title: Code Explainer
3
- emoji: 😻
4
- colorFrom: red
5
- colorTo: purple
6
  sdk: gradio
7
- sdk_version: 6.5.1
 
8
  app_file: app.py
9
  pinned: false
 
 
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: Code Explainer
3
+ emoji: 💻
4
+ colorFrom: green
5
+ colorTo: blue
6
  sdk: gradio
7
+ sdk_version: 5.9.1
8
+ python_version: "3.10"
9
  app_file: app.py
10
  pinned: false
11
+ license: mit
12
+ short_description: AI-powered code explanation and documentation
13
  ---
14
 
15
+ # Code Explainer
16
+
17
+ An AI-powered tool that explains code snippets in plain English. Paste any code and get a clear, educational explanation of what it does, how it works, and key concepts involved.
18
+
19
+ ## Features
20
+
21
+ ### Multi-Language Support
22
+ Supports Python, JavaScript, TypeScript, Java, C++, Go, Rust, and more.
23
+
24
+ ### Explanation Levels
25
+ Choose your expertise level:
26
+ - **Beginner** - Simple explanations with analogies
27
+ - **Intermediate** - Technical details with context
28
+ - **Advanced** - In-depth analysis with edge cases
29
+
30
+ ### Structured Output
31
+ Each explanation includes:
32
+ - **Overview** - What the code does at a high level
33
+ - **Line-by-Line Breakdown** - Detailed explanation of each part
34
+ - **Key Concepts** - Important programming concepts used
35
+ - **Potential Issues** - Common pitfalls or improvements
36
+
37
+ ### Syntax Highlighting
38
+ Code is displayed with proper syntax highlighting for readability.
39
+
40
+ ## How to Use
41
+
42
+ 1. **Paste your code** into the input area
43
+ 2. **Select the language** (or let it auto-detect)
44
+ 3. **Choose explanation level** based on your experience
45
+ 4. **Click Explain** to get your explanation
46
+
47
+ ## Technical Details
48
+
49
+ | Component | Technology |
50
+ |-----------|------------|
51
+ | Web Framework | Gradio 5.9.1 |
52
+ | AI Model | Mistral-7B via HuggingFace Inference API |
53
+ | Code Formatting | Pygments |
54
+
55
+ ## Example Use Cases
56
+
57
+ - **Learning** - Understand unfamiliar code you encounter
58
+ - **Code Review** - Get a second opinion on complex logic
59
+ - **Documentation** - Generate explanations for your codebase
60
+ - **Debugging** - Understand what code is supposed to do
61
+
62
+ ## Limitations
63
+
64
+ - Works best with code snippets under 500 lines
65
+ - Complex multi-file projects may need to be explained piece by piece
66
+ - AI explanations should be verified for critical code
67
+
68
+ ## License
69
+
70
+ MIT
71
+
72
+ ## Author
73
+
74
+ Built by [Lorenzo Scaturchio](https://huggingface.co/gr8monk3ys)
app.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Code Explainer - AI-powered code explanation using HuggingFace Inference API.
3
+ """
4
+
5
+ import gradio as gr
6
+ from huggingface_hub import InferenceClient
7
+ from pygments import highlight
8
+ from pygments.lexers import get_lexer_by_name, guess_lexer
9
+ from pygments.formatters import HtmlFormatter
10
+
11
+ # ---------------------------------------------------------------------------
12
+ # Configuration
13
+ # ---------------------------------------------------------------------------
14
+
15
+ MODEL_ID = "mistralai/Mistral-7B-Instruct-v0.3"
16
+
17
+ LANGUAGES = [
18
+ "Auto-detect",
19
+ "Python",
20
+ "JavaScript",
21
+ "TypeScript",
22
+ "Java",
23
+ "C++",
24
+ "C",
25
+ "Go",
26
+ "Rust",
27
+ "Ruby",
28
+ "PHP",
29
+ "Swift",
30
+ "Kotlin",
31
+ "SQL",
32
+ "Bash",
33
+ "HTML/CSS",
34
+ ]
35
+
36
+ EXPLANATION_LEVELS = {
37
+ "Beginner": "Explain this code in simple terms that a programming beginner would understand. Use analogies and avoid jargon. Focus on the 'what' rather than technical details.",
38
+ "Intermediate": "Explain this code for someone with basic programming knowledge. Include technical details but explain any advanced concepts. Discuss both what the code does and how it works.",
39
+ "Advanced": "Provide a thorough technical analysis of this code. Discuss implementation details, time/space complexity, potential edge cases, and possible improvements or alternatives.",
40
+ }
41
+
42
+ # ---------------------------------------------------------------------------
43
+ # Initialize client
44
+ # ---------------------------------------------------------------------------
45
+
46
+ client = InferenceClient(MODEL_ID)
47
+
48
+ # ---------------------------------------------------------------------------
49
+ # Utility functions
50
+ # ---------------------------------------------------------------------------
51
+
52
+ def detect_language(code: str) -> str:
53
+ """Attempt to detect the programming language."""
54
+ try:
55
+ lexer = guess_lexer(code)
56
+ return lexer.name
57
+ except Exception:
58
+ return "Unknown"
59
+
60
+
61
+ def format_code_html(code: str, language: str) -> str:
62
+ """Apply syntax highlighting to code."""
63
+ try:
64
+ if language == "Auto-detect" or language == "Unknown":
65
+ lexer = guess_lexer(code)
66
+ else:
67
+ lang_map = {
68
+ "JavaScript": "javascript",
69
+ "TypeScript": "typescript",
70
+ "C++": "cpp",
71
+ "HTML/CSS": "html",
72
+ "Bash": "bash",
73
+ }
74
+ lang_key = lang_map.get(language, language.lower())
75
+ lexer = get_lexer_by_name(lang_key)
76
+
77
+ formatter = HtmlFormatter(style="monokai", noclasses=True)
78
+ return highlight(code, lexer, formatter)
79
+ except Exception:
80
+ return f"<pre><code>{code}</code></pre>"
81
+
82
+
83
+ # ---------------------------------------------------------------------------
84
+ # Main explanation function
85
+ # ---------------------------------------------------------------------------
86
+
87
+ def explain_code(code: str, language: str, level: str) -> tuple[str, str]:
88
+ """Generate an explanation for the provided code."""
89
+ if not code.strip():
90
+ return "Please paste some code to explain.", ""
91
+
92
+ # Detect language if auto
93
+ detected_lang = language
94
+ if language == "Auto-detect":
95
+ detected_lang = detect_language(code)
96
+
97
+ # Build prompt
98
+ level_instruction = EXPLANATION_LEVELS.get(level, EXPLANATION_LEVELS["Intermediate"])
99
+
100
+ prompt = f"""You are an expert programming tutor. {level_instruction}
101
+
102
+ Here is the code to explain:
103
+
104
+ ```{detected_lang.lower()}
105
+ {code}
106
+ ```
107
+
108
+ Provide a structured explanation with the following sections:
109
+
110
+ ## Overview
111
+ A brief summary of what this code does (2-3 sentences).
112
+
113
+ ## Step-by-Step Breakdown
114
+ Explain the code section by section, describing what each part does.
115
+
116
+ ## Key Concepts
117
+ List and briefly explain the important programming concepts used in this code.
118
+
119
+ ## Potential Improvements
120
+ Suggest any improvements, best practices, or potential issues to be aware of.
121
+
122
+ Keep your explanation clear, accurate, and educational."""
123
+
124
+ try:
125
+ # Call the inference API
126
+ response = client.text_generation(
127
+ prompt,
128
+ max_new_tokens=1500,
129
+ temperature=0.7,
130
+ top_p=0.95,
131
+ do_sample=True,
132
+ )
133
+
134
+ explanation = response.strip()
135
+
136
+ # Add language badge
137
+ explanation = f"**Detected Language:** `{detected_lang}`\n\n---\n\n{explanation}"
138
+
139
+ # Format the code with syntax highlighting
140
+ formatted_code = format_code_html(code, detected_lang)
141
+
142
+ return explanation, formatted_code
143
+
144
+ except Exception as e:
145
+ error_msg = f"Error generating explanation: {str(e)}"
146
+ return error_msg, format_code_html(code, detected_lang)
147
+
148
+
149
+ # ---------------------------------------------------------------------------
150
+ # Gradio Interface
151
+ # ---------------------------------------------------------------------------
152
+
153
+ EXAMPLE_CODE = '''def fibonacci(n):
154
+ """Generate Fibonacci sequence up to n terms."""
155
+ if n <= 0:
156
+ return []
157
+ elif n == 1:
158
+ return [0]
159
+
160
+ sequence = [0, 1]
161
+ while len(sequence) < n:
162
+ next_num = sequence[-1] + sequence[-2]
163
+ sequence.append(next_num)
164
+
165
+ return sequence
166
+
167
+ # Example usage
168
+ result = fibonacci(10)
169
+ print(result)'''
170
+
171
+ with gr.Blocks(title="Code Explainer", theme=gr.themes.Soft()) as demo:
172
+ gr.Markdown("""
173
+ # Code Explainer
174
+
175
+ Paste any code snippet and get a clear, educational explanation.
176
+ Choose your experience level for tailored explanations.
177
+ """)
178
+
179
+ with gr.Row():
180
+ with gr.Column(scale=1):
181
+ code_input = gr.Code(
182
+ label="Paste Your Code",
183
+ language="python",
184
+ lines=15,
185
+ value=EXAMPLE_CODE,
186
+ )
187
+
188
+ with gr.Row():
189
+ language_dropdown = gr.Dropdown(
190
+ choices=LANGUAGES,
191
+ value="Auto-detect",
192
+ label="Language",
193
+ scale=1,
194
+ )
195
+ level_dropdown = gr.Dropdown(
196
+ choices=list(EXPLANATION_LEVELS.keys()),
197
+ value="Intermediate",
198
+ label="Explanation Level",
199
+ scale=1,
200
+ )
201
+
202
+ explain_btn = gr.Button("Explain Code", variant="primary")
203
+
204
+ with gr.Column(scale=1):
205
+ formatted_code_output = gr.HTML(label="Formatted Code")
206
+
207
+ explanation_output = gr.Markdown(label="Explanation")
208
+
209
+ explain_btn.click(
210
+ fn=explain_code,
211
+ inputs=[code_input, language_dropdown, level_dropdown],
212
+ outputs=[explanation_output, formatted_code_output],
213
+ )
214
+
215
+ gr.Markdown("""
216
+ ---
217
+
218
+ **Model:** Mistral-7B-Instruct via HuggingFace Inference API
219
+
220
+ **Tip:** For best results, include complete functions or logical code blocks.
221
+
222
+ Built by [Lorenzo Scaturchio](https://huggingface.co/gr8monk3ys)
223
+ """)
224
+
225
+ if __name__ == "__main__":
226
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio==5.9.1
2
+ huggingface_hub>=0.25.0
3
+ pygments>=2.17.0