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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import logging
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from langchain import LLMChain, PromptTemplate
|
| 5 |
+
from langchain.memory import ConversationBufferMemory
|
| 6 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 7 |
+
|
| 8 |
+
# Setup logging
|
| 9 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
def load_api_key():
|
| 13 |
+
"""Load API key from Hugging Face Spaces secrets"""
|
| 14 |
+
# In Hugging Face Spaces, use secrets instead of .env files
|
| 15 |
+
api_key = os.getenv("GOOGLE_API_KEY")
|
| 16 |
+
if not api_key:
|
| 17 |
+
raise ValueError("""
|
| 18 |
+
GOOGLE_API_KEY not found in environment variables.
|
| 19 |
+
|
| 20 |
+
To fix this in Hugging Face Spaces:
|
| 21 |
+
1. Go to your Space settings
|
| 22 |
+
2. Click on 'Repository secrets'
|
| 23 |
+
3. Add GOOGLE_API_KEY with your Google API key value
|
| 24 |
+
4. Restart the Space
|
| 25 |
+
""")
|
| 26 |
+
return api_key
|
| 27 |
+
|
| 28 |
+
def initialize_llm():
|
| 29 |
+
"""Initialize the LLM with proper error handling"""
|
| 30 |
+
try:
|
| 31 |
+
api_key = load_api_key()
|
| 32 |
+
os.environ["GOOGLE_API_KEY"] = api_key
|
| 33 |
+
|
| 34 |
+
llm = ChatGoogleGenerativeAI(
|
| 35 |
+
model="gemini-1.5-flash", # Using more stable model for HF
|
| 36 |
+
temperature=0,
|
| 37 |
+
max_tokens=2048
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
# Test the connection
|
| 41 |
+
response = llm.invoke("Test connection - respond with 'OK'")
|
| 42 |
+
logger.info("β
API connection successful!")
|
| 43 |
+
logger.info(f"Response: {response.content}")
|
| 44 |
+
return llm
|
| 45 |
+
|
| 46 |
+
except Exception as e:
|
| 47 |
+
logger.error(f"β API Error: {e}")
|
| 48 |
+
# Return a mock LLM for demo purposes if API fails
|
| 49 |
+
return None
|
| 50 |
+
|
| 51 |
+
# Enhanced prompt template
|
| 52 |
+
template = """You are an expert code reviewer and security analyst specializing in vulnerability detection and secure coding practices.
|
| 53 |
+
|
| 54 |
+
For any code provided, analyze it systematically:
|
| 55 |
+
|
| 56 |
+
**π Code Overview**:
|
| 57 |
+
- Briefly explain what the code does and its purpose
|
| 58 |
+
|
| 59 |
+
**π Security Analysis**:
|
| 60 |
+
- Identify security vulnerabilities with risk levels:
|
| 61 |
+
- π΄ **High Risk**: Critical vulnerabilities that could lead to system compromise
|
| 62 |
+
- π‘ **Medium Risk**: Moderate security concerns that should be addressed
|
| 63 |
+
- π’ **Low Risk**: Minor security improvements
|
| 64 |
+
- Explain potential exploitation methods
|
| 65 |
+
|
| 66 |
+
**β‘ Code Quality Review**:
|
| 67 |
+
- Performance issues and bottlenecks
|
| 68 |
+
- Code readability and maintainability
|
| 69 |
+
- Best practice violations
|
| 70 |
+
- Logic errors or inefficiencies
|
| 71 |
+
|
| 72 |
+
**π οΈ Actionable Recommendations**:
|
| 73 |
+
- Provide specific, implementable fixes
|
| 74 |
+
- Include secure code examples where applicable
|
| 75 |
+
- Suggest architectural improvements
|
| 76 |
+
|
| 77 |
+
For non-code queries, provide relevant security guidance and best practices.
|
| 78 |
+
|
| 79 |
+
**Conversation History:**
|
| 80 |
+
{chat_history}
|
| 81 |
+
|
| 82 |
+
**User Input:** {user_message}
|
| 83 |
+
|
| 84 |
+
**Analysis:**"""
|
| 85 |
+
|
| 86 |
+
def create_llm_chain():
|
| 87 |
+
"""Create the LLM chain with memory"""
|
| 88 |
+
try:
|
| 89 |
+
llm = initialize_llm()
|
| 90 |
+
|
| 91 |
+
if llm is None:
|
| 92 |
+
return None
|
| 93 |
+
|
| 94 |
+
prompt = PromptTemplate(
|
| 95 |
+
input_variables=["chat_history", "user_message"],
|
| 96 |
+
template=template
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
memory = ConversationBufferMemory(
|
| 100 |
+
memory_key="chat_history",
|
| 101 |
+
return_messages=True
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
return LLMChain(
|
| 105 |
+
llm=llm,
|
| 106 |
+
prompt=prompt,
|
| 107 |
+
memory=memory
|
| 108 |
+
)
|
| 109 |
+
except Exception as e:
|
| 110 |
+
logger.error(f"Failed to create LLM chain: {e}")
|
| 111 |
+
return None
|
| 112 |
+
|
| 113 |
+
def get_text_response(user_message, history):
|
| 114 |
+
"""Generate response with proper error handling"""
|
| 115 |
+
try:
|
| 116 |
+
# Check if LLM chain is available
|
| 117 |
+
if llm_chain is None:
|
| 118 |
+
return """
|
| 119 |
+
π« **API Configuration Error**
|
| 120 |
+
|
| 121 |
+
The Google Gemini API is not properly configured. To use this Space:
|
| 122 |
+
|
| 123 |
+
1. **Fork this Space** to your own Hugging Face account
|
| 124 |
+
2. Go to **Settings** β **Repository secrets**
|
| 125 |
+
3. Add `GOOGLE_API_KEY` with your Google AI Studio API key
|
| 126 |
+
4. Get your API key from: https://makersuite.google.com/app/apikey
|
| 127 |
+
5. **Restart the Space**
|
| 128 |
+
|
| 129 |
+
This is a demo of a code security analyzer that would normally use Google's Gemini AI.
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
# Validate input
|
| 133 |
+
if not user_message or not user_message.strip():
|
| 134 |
+
return "β οΈ Please provide code to analyze or ask a security-related question."
|
| 135 |
+
|
| 136 |
+
# Check for potentially sensitive information
|
| 137 |
+
sensitive_keywords = ['password', 'api_key', 'secret', 'token']
|
| 138 |
+
if any(keyword in user_message.lower() for keyword in sensitive_keywords):
|
| 139 |
+
logger.warning("User input contains potentially sensitive information")
|
| 140 |
+
|
| 141 |
+
response = llm_chain.predict(user_message=user_message.strip())
|
| 142 |
+
return response
|
| 143 |
+
|
| 144 |
+
except Exception as e:
|
| 145 |
+
logger.error(f"Error generating response: {e}")
|
| 146 |
+
return f"""
|
| 147 |
+
π« **Error Analysis**
|
| 148 |
+
|
| 149 |
+
I encountered an error while analyzing your request: {str(e)}
|
| 150 |
+
|
| 151 |
+
**Possible solutions:**
|
| 152 |
+
1. Check if your Google API key is valid
|
| 153 |
+
2. Ensure you have credits remaining in your Google AI account
|
| 154 |
+
3. Try again with a shorter input
|
| 155 |
+
4. Contact the Space owner if the issue persists
|
| 156 |
+
"""
|
| 157 |
+
|
| 158 |
+
def create_interface():
|
| 159 |
+
"""Create the Gradio interface optimized for Hugging Face"""
|
| 160 |
+
examples = [
|
| 161 |
+
"Review this SQL query for injection vulnerabilities: SELECT * FROM users WHERE id = '" + "user_input" + "'",
|
| 162 |
+
"Analyze this Python authentication function:\n```python\ndef login(username, password):\n if username == 'admin' and password == 'password123':\n return True\n return False\n```",
|
| 163 |
+
"What are the OWASP Top 10 web application security risks?",
|
| 164 |
+
"How can I securely store passwords in my application?",
|
| 165 |
+
"Check this JavaScript for XSS vulnerabilities: document.innerHTML = userInput"
|
| 166 |
+
]
|
| 167 |
+
|
| 168 |
+
# Custom CSS for better appearance on HF
|
| 169 |
+
custom_css = """
|
| 170 |
+
.gradio-container {
|
| 171 |
+
max-width: 1200px !important;
|
| 172 |
+
}
|
| 173 |
+
.message-row {
|
| 174 |
+
justify-content: space-between !important;
|
| 175 |
+
}
|
| 176 |
+
footer {
|
| 177 |
+
visibility: hidden;
|
| 178 |
+
}
|
| 179 |
+
"""
|
| 180 |
+
|
| 181 |
+
interface = gr.ChatInterface(
|
| 182 |
+
get_text_response,
|
| 183 |
+
examples=examples,
|
| 184 |
+
title="π Code Security Analyzer & Vulnerability Scanner",
|
| 185 |
+
description="""
|
| 186 |
+
**Professional code security analysis powered by Google Gemini AI**
|
| 187 |
+
|
| 188 |
+
β
**Features:**
|
| 189 |
+
- π Vulnerability detection with risk assessment
|
| 190 |
+
- π Code quality review and best practices analysis
|
| 191 |
+
- π‘οΈ Secure coding recommendations
|
| 192 |
+
- π Multi-language support (Python, JavaScript, Java, C++, etc.)
|
| 193 |
+
- π OWASP compliance guidance
|
| 194 |
+
|
| 195 |
+
β οΈ **Security Notice:** Do not submit production secrets, passwords, or sensitive data.
|
| 196 |
+
|
| 197 |
+
---
|
| 198 |
+
|
| 199 |
+
**π To use this Space:**
|
| 200 |
+
1. Fork this Space to your account
|
| 201 |
+
2. Add your Google AI Studio API key in Settings β Repository secrets
|
| 202 |
+
3. Set the secret name as `GOOGLE_API_KEY`
|
| 203 |
+
4. Get your API key: https://makersuite.google.com/app/apikey
|
| 204 |
+
""",
|
| 205 |
+
type='messages',
|
| 206 |
+
theme=gr.themes.Soft(
|
| 207 |
+
primary_hue="blue",
|
| 208 |
+
secondary_hue="gray",
|
| 209 |
+
font=gr.themes.GoogleFont("Inter")
|
| 210 |
+
),
|
| 211 |
+
css=custom_css,
|
| 212 |
+
analytics_enabled=False, # Disable analytics for HF Spaces
|
| 213 |
+
cache_examples=False # Disable caching for better performance
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
return interface
|
| 217 |
+
|
| 218 |
+
# Initialize the LLM chain
|
| 219 |
+
llm_chain = None
|
| 220 |
+
try:
|
| 221 |
+
llm_chain = create_llm_chain()
|
| 222 |
+
if llm_chain:
|
| 223 |
+
logger.info("π Code Security Analyzer initialized successfully!")
|
| 224 |
+
else:
|
| 225 |
+
logger.warning("β οΈ Running in demo mode - API not configured")
|
| 226 |
+
except Exception as e:
|
| 227 |
+
logger.error(f"Failed to initialize application: {e}")
|
| 228 |
+
|
| 229 |
+
# Create and launch the interface
|
| 230 |
+
if __name__ == "__main__":
|
| 231 |
+
try:
|
| 232 |
+
demo = create_interface()
|
| 233 |
+
demo.launch(
|
| 234 |
+
show_error=True,
|
| 235 |
+
share=False, # Set to False for HF Spaces
|
| 236 |
+
enable_queue=True, # Enable queue for better performance
|
| 237 |
+
max_threads=10 # Limit concurrent users
|
| 238 |
+
)
|
| 239 |
+
except Exception as e:
|
| 240 |
+
logger.error(f"Failed to launch application: {e}")
|
| 241 |
+
# Still try to launch a basic interface
|
| 242 |
+
def error_interface(message, history):
|
| 243 |
+
return f"Application failed to initialize: {str(e)}"
|
| 244 |
+
|
| 245 |
+
gr.ChatInterface(
|
| 246 |
+
error_interface,
|
| 247 |
+
title="β Configuration Error",
|
| 248 |
+
description="Please check the application logs and configuration."
|
| 249 |
+
).launch()
|