sreelekhaputta2 commited on
Commit
ae23fa1
·
verified ·
1 Parent(s): 120e535

Update app.py

Browse files

"An AI-powered multi-language code documentation generator that produces clear, context-aware summaries and exports them in Markdown or PDF formats."

Files changed (1) hide show
  1. app.py +269 -0
app.py CHANGED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
4
+ import tensorflow as tf
5
+ import gradio as gr
6
+ from fpdf import FPDF
7
+ import pandas as pd
8
+
9
+ # Load Features from CSV (curate a subset for demo clarity)
10
+ features_df = pd.read_csv("Feature-Description.csv")
11
+ key_features = [
12
+ "Automatic Code Analysis",
13
+ "Context-Aware Documentation",
14
+ "Real-Time Updates",
15
+ "Dependency Mapping",
16
+ "API Documentation",
17
+ "Test Suite Generation",
18
+ "UML Diagram Generation",
19
+ "Bug/Issue Identification",
20
+ "Natural Language Explanations",
21
+ "Customizable Output Formats",
22
+ "Language Agnostic",
23
+ "Automated Refreshes",
24
+ "Analytics and Insights",
25
+ "Automated Code Summaries"
26
+ ]
27
+ features_list = [row for row in features_df.to_dict(orient="records") if row["Feature"] in key_features]
28
+
29
+ def features_html():
30
+ html = "<ul style='margin:0; padding-left:1.2em; font-size:16px; color:#f4f6fa;'>"
31
+ for f in features_list:
32
+ html += f"<li><b>{f['Feature']}</b>: {f['Description']}</li>"
33
+ html += "</ul>"
34
+ return html
35
+
36
+ model_name = "Salesforce/codet5-base"
37
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
38
+ model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
39
+
40
+ class CodeComplexityScorer(tf.keras.Model):
41
+ def __init__(self):
42
+ super().__init__()
43
+ self.dense1 = tf.keras.layers.Dense(32, activation='relu')
44
+ self.dense2 = tf.keras.layers.Dense(1, activation='sigmoid')
45
+ def call(self, inputs):
46
+ x = self.dense1(inputs)
47
+ score = self.dense2(x)
48
+ return score
49
+
50
+ complexity_model = CodeComplexityScorer()
51
+
52
+ def extract_code_features(code_text):
53
+ length = len(code_text)
54
+ lines = code_text.count('\n') + 1
55
+ words = code_text.split()
56
+ avg_word_len = sum(len(w) for w in words) / (len(words) + 1)
57
+ features = tf.constant([[length/1000, lines/50, avg_word_len/20]], dtype=tf.float32)
58
+ return features
59
+
60
+ LANG_PROMPTS = {
61
+ "Python": "summarize Python code:",
62
+ "JavaScript": "summarize JavaScript code:",
63
+ "Java": "summarize Java code:",
64
+ "Other": "summarize code:",
65
+ }
66
+
67
+ def automatic_code_analysis(code_text):
68
+ return f"Code contains {code_text.count(chr(10))+1} lines and {len(code_text)} characters."
69
+
70
+ def context_aware_documentation(code_text):
71
+ return "Generates context-aware, readable documentation (demo placeholder)."
72
+
73
+ def bug_issue_identification(code_text):
74
+ return "No obvious issues detected (demo placeholder)."
75
+
76
+ def automated_code_summaries(code_text):
77
+ return "Provides concise summaries of code modules (demo placeholder)."
78
+
79
+ feature_functions = {
80
+ "Automatic Code Analysis": automatic_code_analysis,
81
+ "Context-Aware Documentation": context_aware_documentation,
82
+ "Bug/Issue Identification": bug_issue_identification,
83
+ "Automated Code Summaries": automated_code_summaries,
84
+ }
85
+
86
+ def generate_documentation(code_text, language, export_format, selected_features):
87
+ features = extract_code_features(code_text)
88
+ complexity_score = complexity_model(features).numpy()[0][0]
89
+ prompt = LANG_PROMPTS.get(language, LANG_PROMPTS["Other"])
90
+ input_text = f"{prompt} {code_text.strip()}"
91
+ inputs = tokenizer.encode(input_text, return_tensors="pt", max_length=512, truncation=True)
92
+ summary_ids = model.generate(inputs, max_length=128, num_beams=5, early_stopping=True)
93
+ summary = tokenizer.decode(summary_ids[0], skip_special_tokens=True)
94
+ extra_sections = ""
95
+ for feature in selected_features:
96
+ if feature in feature_functions:
97
+ extra_sections += f"\n**{feature}:**\n{feature_functions[feature](code_text)}"
98
+ doc_output = f"""### AI-Generated Documentation
99
+
100
+ {summary}
101
+
102
+ **Code Complexity Score:** {complexity_score:.2f} (0=low,1=high)
103
+ {extra_sections}
104
+ """
105
+ if export_format == "Markdown":
106
+ return doc_output
107
+ elif export_format == "PDF":
108
+ pdf_filename = "/tmp/generated_doc.pdf"
109
+ pdf = FPDF()
110
+ pdf.add_page()
111
+ pdf.set_font("Arial", size=12)
112
+ for line in doc_output.split('\n'):
113
+ pdf.cell(0, 10, txt=line, ln=True)
114
+ pdf.output(pdf_filename)
115
+ return pdf_filename
116
+ else:
117
+ return doc_output
118
+
119
+ def process_uploaded_file(uploaded_file, language, export_format, selected_features):
120
+ code_bytes = uploaded_file.read()
121
+ code_text = code_bytes.decode("utf-8", errors="ignore")
122
+ return generate_documentation(code_text, language, export_format, selected_features)
123
+
124
+ # --- CSS: Use .gradio-container for full-page background image ---
125
+ custom_css = """
126
+ .gradio-container {
127
+ background-image: url('https://media.istockphoto.com/photos/programming-code-abstract-technology-background-of-software-developer-picture-id1201405775?b=1&k=20&m=1201405775&s=170667a&w=0&h=XZ-tUfHvW5IRT30nMm7bAbbWrqkGQ-WT8XSS8Pab-eA=');
128
+ background-repeat: no-repeat;
129
+ background-position: center center;
130
+ background-attachment: fixed;
131
+ background-size: cover;
132
+ min-height: 100vh;
133
+ }
134
+ #container {
135
+ background: rgba(16, 24, 40, 0.85);
136
+ border-radius: 22px;
137
+ padding: 2.5rem 3.5rem;
138
+ max-width: 900px;
139
+ margin: 2rem auto 3rem auto;
140
+ box-shadow: 0 12px 48px 0 rgba(60,120,220,0.28), 0 1.5px 12px 0 rgba(0,0,0,0.15);
141
+ color: #f4f6fa !important;
142
+ backdrop-filter: blur(7px);
143
+ border: 2.5px solid rgba(0,255,255,0.10);
144
+ }
145
+ #animated-header {
146
+ font-size: 2.6em !important;
147
+ font-weight: 900;
148
+ text-align: center;
149
+ margin-bottom: 1em;
150
+ background: linear-gradient(270deg, #00f2fe, #4facfe, #43e97b, #fa709a, #fee140, #00f2fe);
151
+ background-size: 800% 800%;
152
+ -webkit-background-clip: text;
153
+ -webkit-text-fill-color: transparent;
154
+ animation: gradientShift 12s ease-in-out infinite;
155
+ letter-spacing: 2px;
156
+ text-shadow: 0 2px 8px rgba(0,255,255,0.18);
157
+ }
158
+ @keyframes gradientShift {
159
+ 0%{background-position:0% 50%;}
160
+ 50%{background-position:100% 50%;}
161
+ 100%{background-position:0% 50%;}
162
+ }
163
+ #feature-panel {
164
+ background: rgba(34, 49, 63, 0.95);
165
+ border-radius: 14px;
166
+ padding: 1.2rem 1.8rem;
167
+ margin-bottom: 1.5rem;
168
+ box-shadow: 0 4px 18px rgba(0,255,255,0.10);
169
+ max-height: 200px;
170
+ overflow-y: auto;
171
+ font-size: 1.13em;
172
+ line-height: 1.5em;
173
+ color: #f4f6fa !important;
174
+ border: 2px solid #00f2fe;
175
+ animation: fadeInUp 1.2s ease forwards, neon-glow 2.5s infinite alternate;
176
+ }
177
+ @keyframes fadeInUp {
178
+ from {opacity: 0; transform: translateY(20px);}
179
+ to {opacity: 1; transform: translateY(0);}
180
+ }
181
+ @keyframes neon-glow {
182
+ 0% { box-shadow: 0 0 8px #00f2fe, 0 0 16px #00f2fe70; border-color: #00f2fe;}
183
+ 100% { box-shadow: 0 0 16px #43e97b, 0 0 32px #43e97b70; border-color: #43e97b;}
184
+ }
185
+ #generate-btn {
186
+ background: linear-gradient(90deg, #43e97b, #38f9d7, #00f2fe);
187
+ color: #192a56 !important;
188
+ font-weight: 800;
189
+ border-radius: 14px;
190
+ padding: 0.9em 2.2em;
191
+ font-size: 1.25em;
192
+ border: none;
193
+ box-shadow: 0 6px 24px 0 rgba(0,255,255,0.22);
194
+ transition: all 0.3s cubic-bezier(.4,2,.6,1);
195
+ letter-spacing: 1px;
196
+ outline: none;
197
+ }
198
+ #generate-btn:hover {
199
+ background: linear-gradient(90deg, #fa709a, #fee140);
200
+ color: #192a56 !important;
201
+ box-shadow: 0 8px 32px rgba(250,112,154,0.22);
202
+ transform: scale(1.06);
203
+ cursor: pointer;
204
+ }
205
+ #credits {
206
+ text-align: center;
207
+ margin-top: 2.5rem;
208
+ font-size: 1.15em;
209
+ color: #fee140;
210
+ font-weight: 800;
211
+ letter-spacing: 0.08em;
212
+ animation: fadeIn 2s ease forwards;
213
+ text-shadow: 0 2px 8px #fa709a50;
214
+ }
215
+ @media (max-width: 600px) {
216
+ #container {
217
+ padding: 1rem 0.5rem;
218
+ margin: 1rem;
219
+ }
220
+ #animated-header {
221
+ font-size: 1.4em !important;
222
+ }
223
+ #feature-panel {
224
+ padding: 0.7rem 0.7rem;
225
+ font-size: 1em;
226
+ }
227
+ }
228
+ """
229
+
230
+ with gr.Blocks(css=custom_css, elem_id="container") as demo:
231
+ gr.HTML("<div id='animated-header'>AI-Powered Code Documentation Generator</div>")
232
+ with gr.Row():
233
+ gr.HTML(f"<div id='feature-panel'><b>Supported Features (scroll if needed):</b>{features_html()}</div>")
234
+ file_input = gr.File(label="Upload Code File (.py, .js, .java)", file_types=[".py", ".js", ".java"])
235
+ code_input = gr.Textbox(label="Or Paste Code Here", lines=8, max_lines=15, placeholder="Paste your code snippet here...")
236
+ language_dropdown = gr.Dropdown(label="Select Language", choices=["Python", "JavaScript", "Java", "Other"], value="Python")
237
+ export_dropdown = gr.Dropdown(label="Export Format", choices=["Markdown", "PDF"], value="Markdown")
238
+ feature_options = gr.CheckboxGroup(
239
+ label="Select Features to Include",
240
+ choices=[f["Feature"] for f in features_list],
241
+ value=["Automatic Code Analysis", "Context-Aware Documentation", "Bug/Issue Identification"],
242
+ interactive=True,
243
+ container=False,
244
+ show_label=True,
245
+ )
246
+ generate_btn = gr.Button("Generate Documentation", elem_id="generate-btn")
247
+ output_box = gr.Textbox(label="Generated Documentation", lines=10, max_lines=20, interactive=False, show_copy_button=True)
248
+ pdf_output = gr.File(label="Download PDF", visible=False)
249
+ gr.HTML("<div id='credits'>Credits: Sreelekha Putta</div>")
250
+
251
+ def on_generate(file_obj, code_str, language, export_format, selected_features):
252
+ if file_obj is not None:
253
+ result = process_uploaded_file(file_obj, language, export_format, selected_features)
254
+ elif code_str.strip() != "":
255
+ result = generate_documentation(code_str, language, export_format, selected_features)
256
+ else:
257
+ return "Please upload a file or paste code to generate documentation.", None
258
+ if export_format == "PDF":
259
+ return None, gr.update(value=result, visible=True)
260
+ else:
261
+ return result, gr.update(visible=False)
262
+
263
+ generate_btn.click(
264
+ on_generate,
265
+ inputs=[file_input, code_input, language_dropdown, export_dropdown, feature_options],
266
+ outputs=[output_box, pdf_output]
267
+ )
268
+
269
+ demo.launch()