Caddis12's picture
Update app.py
d95d846 verified
Raw History Blame Contribute Delete
12.4 kB
# ============================================ # CADDIS DEVELOPER AI # Advanced AI Coding Assistant # ============================================ import gradio as gr from gradio import Progress from transformers import pipeline import os import re import zipfile import tempfile import shutil from pathlib import Path # ============================================ # LOAD AI MODEL # ============================================ MODEL_NAME = "Qwen/Qwen2.5-Coder-3B-Instruct" coder = pipeline( "text-generation", model=MODEL_NAME, dtype="auto", device_map="auto" ) print("βœ… Caddis Developer AI Loaded") # ============================================ # CHAT MEMORY # ============================================ conversation_memory = [] def build_memory(): history_text = "" for user, ai in conversation_memory[-5:]: history_text += f""" User: {user} Assistant: {ai} """ return history_text # ============================================ # READ FILE # ============================================ def read_file(file): if file is None: return "" try: with open( file.name, "r", encoding="utf-8", errors="ignore" ) as f: return f.read() except: return "" # ============================================ # READ MULTIPLE FILES # ============================================ def read_project(files): project = "" if files is None: return project for file in files: try: content = read_file(file) project += f""" ======================== FILE: {file.name} ======================== {content} """ except: pass return project # ============================================ # CODE ANALYZER # ============================================ def analyze_code(code): lines = code.split("\n") stats = { "Lines": len(lines), "Functions": len( re.findall( r"\bdef\b|\bfunction\b", code ) ), "Classes": len( re.findall( r"\bclass\b", code ) ), "Imports": len( re.findall( r"\bimport\b|\bfrom\b", code ) ), "Comments": len( [ x for x in lines if x.strip().startswith("#") ] ) } result = """ ## πŸ“Š Code Analysis """ for key,value in stats.items(): result += f""" **{key}:** {value} """ return result # ============================================ # CADDIS AI CODING ENGINE # ============================================ def coding_ai( language, task, prompt, uploaded_file, project_files, history, progress=gr.Progress() ): # Read single file single_file_code = read_file(uploaded_file) progress(0.1, desc="πŸ“‚ Reading uploaded file...") # Read project files project_code = read_project(project_files) progress(0.3, desc="πŸ“ Reading project files...") # Previous conversation memory = build_memory() progress(0.5, desc="🧠 Preparing AI prompt...") full_prompt = f""" You are Caddis Developer AI. You are an expert software engineer. Your job: - Generate code - Debug programs - Explain code - Optimize applications - Refactor software - Review projects - Suggest improvements Programming Language: {language} Task: {task} Previous Conversation: {memory} User Request: {prompt} Single Uploaded File: {single_file_code} Project Files: {project_code} Instructions: 1. Give professional developer answers. 2. Include code when necessary. 3. Explain important parts. 4. Follow best programming practices. 5. If reviewing code, identify problems and improvements. Assistant: """ progress(0.7, desc="πŸ€– Generating code...") response = coder( full_prompt, max_new_tokens=350, temperature=0.7, do_sample=True ) answer = response[0]["generated_text"] progress(1.0, desc="βœ… Done!") answer = answer.replace( full_prompt, "" ) # Save memory conversation_memory.append( ( prompt, answer ) ) return answer.strip() # ============================================ # PROJECT ANALYZER # ============================================ def analyze_project(files): if files is None: return "No project uploaded" total_files = len(files) extensions = {} total_lines = 0 for file in files: ext = Path( file.name ).suffix extensions[ext] = ( extensions.get(ext,0)+1 ) try: content = read_file(file) total_lines += len( content.split("\n") ) except: pass result = """ # 🧠 Project Understanding """ result += f""" **Total Files:** {total_files} **Total Lines:** {total_lines} ## File Types """ for key,value in extensions.items(): result += f""" {key}: {value} files """ return result # ============================================ # DOWNLOAD GENERATED CODE # ============================================ def save_generated_code(answer): filename = "caddis_generated_code.txt" with open( filename, "w", encoding="utf-8" ) as f: f.write(answer) return filename # ============================================ # CLEAR CHAT MEMORY # ============================================ def clear_memory(): conversation_memory.clear() return "" # ============================================ # CUSTOM CSS # ============================================ css = """ body { background:#0d1117; } .gradio-container { max-width:1400px !important; } .header { text-align:center; padding:20px; } .header h1 { font-size:45px; } .subtitle { color:#8b949e; font-size:18px; } .panel { background:#161b22; border-radius:15px; padding:15px; border:1px solid #30363d; } .footer { text-align:center; color:#8b949e; margin-top:30px; } """ # ============================================ # GRADIO APPLICATION # ============================================ with gr.Blocks() as demo: gr.HTML( f""" <style> {css} </style> """ ) gr.Markdown( """ # πŸ’» Caddis Developer AI """ ) # HEADER gr.Markdown( """ <div class="header"> # πŸ’» Caddis Developer AI <div class="subtitle"> AI Software Engineering Assistant Generate β€’ Debug β€’ Explain β€’ Optimize β€’ Review </div> </div> """ ) # MAIN SETTINGS with gr.Row(): with gr.Column(scale=1): language = gr.Dropdown( choices=[ "Python", "Java", "C++", "C", "C#", "JavaScript", "TypeScript", "HTML", "CSS", "SQL", "PHP", "Go", "Rust", "Kotlin" ], value="Python", label="🌐 Language" ) task = gr.Dropdown( choices=[ "Generate Code", "Debug Code", "Explain Code", "Optimize Code", "Refactor Code", "Code Review", "Generate Tests" ], value="Generate Code", label="πŸ›  Developer Task" ) with gr.Column(scale=2): prompt = gr.Textbox( label="πŸ“ Coding Request", lines=6, placeholder= "Example: Build a Flask authentication system" ) # FILE SECTION with gr.Tab("πŸ“ Project Files"): uploaded_file = gr.File( label="Upload Single Code File", file_types=[ ".py", ".java", ".cpp", ".js", ".html", ".css", ".sql" ] ) project_files = gr.File( label="Upload Complete Project", file_count="multiple" ) analyze_project_btn = gr.Button( "🧠 Analyze Project" ) project_output = gr.Markdown() # EDITOR TAB with gr.Tab("πŸ–₯️ Code Editor"): code_editor = gr.Code( label="Developer Editor", language="python", lines=20 ) editor_info = gr.Markdown( """ VS Code style editor. Paste or load code here. """ ) # CHAT TAB with gr.Tab("πŸ’¬ AI Assistant"): chatbot = gr.Chatbot( height=500, label="Caddis AI Chat" ) # ACTIONS with gr.Row(): generate_btn = gr.Button( "πŸš€ Generate", variant="primary" ) clear_btn = gr.Button( "πŸ—‘ Clear" ) download_btn = gr.Button( "πŸ“₯ Download" ) # OUTPUT ai_output = gr.Markdown( label="πŸ€– AI Response" ) analysis_output = gr.Markdown( label="πŸ“Š Code Analysis" ) download_file = gr.File( label="Generated File" ) # EXAMPLES gr.Markdown( """ ## πŸ“š Quick Examples 🐍 Create a Python calculator 🌐 Build a Flask API πŸ—„ Create SQL database πŸ” Build authentication system 🐞 Debug this code """ ) # ======================================== # BUTTON CONNECTIONS # ======================================== generate_btn.click( coding_ai, inputs=[ language, task, prompt, uploaded_file, project_files, chatbot ], outputs=ai_output ) analyze_project_btn.click( analyze_project, inputs=project_files, outputs=project_output ) download_btn.click( save_generated_code, inputs=ai_output, outputs=download_file ) clear_btn.click( clear_memory, outputs=ai_output ) # FOOTER gr.Markdown( """ <div class="footer"> --- πŸ’» Caddis Developer AI v1.0 Powered by: Python | Hugging Face | Qwen | Gradio Created by Kyambadde Grrald </div> """ ) # ============================================ # LAUNCH # ============================================ demo.launch()
# ============================================
# CADDIS DEVELOPER AI
# Advanced AI Coding Assistant
# ============================================
import gradio as gr
from gradio import Progress
from transformers import pipeline
import os
import re
import zipfile
import tempfile
import shutil
from pathlib import Path
# ============================================
# LOAD AI MODEL
# ============================================
MODEL_NAME = "Qwen/Qwen2.5-Coder-3B-Instruct"
coder = pipeline(
"text-generation",
model=MODEL_NAME,
dtype="auto",
device_map="auto"
)
print("βœ… Caddis Developer AI Loaded")
# ============================================
# CHAT MEMORY
# ============================================
conversation_memory = []
def build_memory():
history_text = ""
for user, ai in conversation_memory[-5:]:
history_text += f"""
User:
{user}
Assistant:
{ai}
"""
return history_text
# ============================================
# READ FILE
# ============================================
def read_file(file):
if file is None:
return ""
try:
with open(
file.name,
"r",
encoding="utf-8",
errors="ignore"
) as f:
return f.read()
except:
return ""
# ============================================
# READ MULTIPLE FILES
# ============================================
def read_project(files):