Spaces:
Sleeping
Sleeping
File size: 5,790 Bytes
0f95125 | 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 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | const express = require("express");
const { Pool } = require("pg");
const dns = require("dns");
const cors = require("cors");
const axios = require("axios");
const path = require("path");
require("dotenv").config({ path: path.join(__dirname, "../../.env") });
const app = express();
app.use(express.json());
app.use(cors());
// Nuclear IPv4 Enforcement: Resolve Hostname to IP immediately
const dbURL = new URL(process.env.DATABASE_URL);
dns.lookup(dbURL.hostname, { family: 4 }, (err, address) => {
if (err) {
console.error("β DNS Lookup Error:", err);
process.exit(1); // Fail fast
}
console.log(`π‘ Database hostname resolved to IPv4: ${address}`);
const db = new Pool({
host: address,
port: dbURL.port,
user: dbURL.username,
password: decodeURIComponent(dbURL.password),
database: dbURL.pathname.split("/")[1],
ssl: { rejectUnauthorized: false }
});
db.on("connect", () => {
console.log("π’ Connected to Supabase via IPv4.");
});
// Export db for routes (if needed) or just define routes inside
setupRoutes(db);
});
function setupRoutes(db) {
// Authentication route for login/signup
app.post("/auth", async (req, res) => {
const { username, password, action } = req.body;
try {
if (action === "signup") {
const results = await db.query(
"INSERT INTO users (username, password) VALUES ($1, $2) RETURNING id",
[username, password]
);
res.json({ success: true, message: "Signup successful!", userId: results.rows[0].id });
} else {
const results = await db.query(
"SELECT id FROM users WHERE username = $1 AND password = $2",
[username, password]
);
if (results.rows.length > 0) {
res.json({ success: true, message: "Login successful!", userId: results.rows[0].id });
} else {
res.json({ success: false, message: "Invalid credentials." });
}
}
} catch (err) {
console.error("Database error details:", err);
res.json({ success: false, message: `DB Error: ${err.message}` });
}
});
// Route to store user option data
app.post("/store-option", async (req, res) => {
const { userId, option, language, codePrompt, modifyCode, modifyLogic } = req.body;
try {
let pythonResponse = null;
let finalPrompt = "";
if (option === "Generate Code") {
finalPrompt = codePrompt;
const targetUrl = process.env.AI_AGENT_URL || "http://127.0.0.1:8000/process-request";
console.log(`π‘ Sending request to: ${targetUrl}`);
pythonResponse = await axios.post(targetUrl, {
taskType: "generate",
prompt: finalPrompt,
});
}
else if (option === "Modify Code") {
finalPrompt = modifyCode;
pythonResponse = await axios.post(process.env.AI_AGENT_URL || "http://127.0.0.1:8000/process-request", {
taskType: "modify",
prompt: finalPrompt,
});
}
const aiOutput = pythonResponse.data.result;
// Store in normalized activity table
await db.query(
"INSERT INTO user_activity (user_id, user_option, language, qn, modify_code_input, modify_code_logic, output) VALUES ($1, $2, $3, $4, $5, $6, $7)",
[
userId,
option,
language || null,
finalPrompt,
(option === "Modify Code" ? modifyCode : null),
(option === "Modify Code" ? modifyLogic : null),
aiOutput
]
);
res.json({
success: true,
message: `${option} data stored successfully!`,
aiOutput: aiOutput
});
} catch (error) {
console.error("Error in store-option:", error);
res.json({ success: false, message: "Error processing request." });
}
});
// Route to analyze code efficiency with scores for visual charts
app.post("/analyze-code", async (req, res) => {
const { userId, originalCode, modifiedCode } = req.body;
try {
const analysisPrompt = `You are a code efficiency analyzer. Compare the ORIGINAL and MODIFIED code below and provide a detailed efficiency analysis.
ORIGINAL CODE:
${originalCode}
MODIFIED CODE:
${modifiedCode}
IMPORTANT: You MUST include numerical scores in your analysis. Use the exact format "Label: X/10" for each metric. Include ALL of the following scored sections:
TIME COMPLEXITY:
- Time Original: [score]/10 β [analysis]
- Time Modified: [score]/10 β [analysis]
- Best/Average/Worst case analysis
SPACE COMPLEXITY:
- Space Original: [score]/10 β [analysis]
- Space Modified: [score]/10 β [analysis]
EXECUTION SPEED:
- Speed Original: [score]/10 β [assessment]
- Speed Modified: [score]/10 β [assessment]
- Bottlenecks identified
CODE READABILITY:
- Readability Original: [score]/10 β [assessment]
- Readability Modified: [score]/10 β [assessment]
MAINTAINABILITY:
- Maintainability Original: [score]/10 β [assessment]
- Maintainability Modified: [score]/10 β [assessment]
BEST PRACTICES:
- Practices Original: [score]/10 β [compliance]
- Practices Modified: [score]/10 β [compliance]
SUMMARY: [Overall comparative summary]
OVERALL EFFICIENCY SCORE: [score]/10 β [brief justification]
Higher scores = better efficiency. Be precise with your /10 ratings.`;
const pythonResponse = await axios.post(process.env.AI_AGENT_URL || "http://localhost:8000/process-request", {
taskType: "analyze",
prompt: analysisPrompt,
});
res.json({
success: true,
message: "Analysis complete!",
analysisResult: pythonResponse.data.result,
});
} catch (error) {
console.error("Error analyzing code:", error);
res.json({ success: false, message: "Error analyzing code. Please try again later." });
}
});
// Start the server on port 5003
app.listen(5003, () => console.log("Server running on port 5003"));
}
|