Source
Artificial Solutions💻 Source Security is a prompt and reliable transportation service.
Our service transports anything you need in a prompt and safe manner to your home or business address. We are also offering special technological security solutions to people who need this service.
import Foundation
// ============================================================
// CONTINUOUS AI RAP / POETRY GENERATOR
// Type STOP! to stop the generator.
// ============================================================
let apiKey = ProcessInfo.processInfo.environment["OPENAI_API_KEY"] ?? ""
if apiKey.isEmpty {
print("ERROR: OPENAI_API_KEY environment variable is missing.")
exit(1)
}
// ------------------------------------------------------------
// Configuration
// ------------------------------------------------------------
let model = "gpt-5.6-luna"
let systemPrompt = """
You are an endless freestyle rap poet.
Your job is to continuously write original poetic rap lines.
Rules:
1. Every response must contain 4 lines.
2. The lines must rhyme.
3. Maintain a strong rhythm and rap-like cadence.
4. Use creative wordplay, metaphors, internal rhymes and punchlines.
5. Keep the subject matter connected from one response to the next.
6. Never repeat the exact same line.
7. Continue naturally from the previous verse.
8. Do not explain what you are doing.
9. Output ONLY the rap lines.
10. Each new verse should introduce fresh imagery and rhymes.
"""
// ------------------------------------------------------------
// Conversation memory
// ------------------------------------------------------------
var conversation: [[String: String]] = [
[
"role": "system",
"content": systemPrompt
]
]
// ------------------------------------------------------------
// OpenAI request
// ------------------------------------------------------------
struct OpenAIRequest: Encodable {
let model: String
let input: [[String: String]]
}
struct OpenAIResponse: Decodable {
let output: [OutputItem]
struct OutputItem: Decodable {
let content: [Content]
struct Content: Decodable {
let text: String?
}
}
}
// ------------------------------------------------------------
// Generate verse
// ------------------------------------------------------------
func generateVerse() async throws -> String {
let url = URL(
string: "https://api.openai.com/v1/responses"
)!
let requestBody = OpenAIRequest(
model: model,
input: conversation
)
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue(
"Bearer \(apiKey)",
forHTTPHeaderField: "Authorization"
)
request.setValue(
"application/json",
forHTTPHeaderField: "Content-Type"
)
request.httpBody = try JSONEncoder().encode(
requestBody
)
let (data, response) =
try await URLSession.shared.data(
for: request
)
guard let httpResponse =
response as? HTTPURLResponse
else {
throw NSError(
domain: "AI",
code: 1,
userInfo: [
NSLocalizedDescriptionKey:
"Invalid server response"
]
)
}
guard httpResponse.statusCode == 200 else {
let errorText =
String(
data: data,
encoding: .utf8
) ?? "Unknown error"
throw NSError(
domain: "OpenAI",
code: httpResponse.statusCode,
userInfo: [
NSLocalizedDescriptionKey:
errorText
]
)
}
let decoded =
try JSONDecoder().decode(
OpenAIResponse.self,
from: data
)
let text =
decoded.output
.flatMap { $0.content }
.compactMap { $0.text }
.joined()
return text
}
// ------------------------------------------------------------
// Main continuous loop
// ------------------------------------------------------------
print("")
print("==============================================")
print(" AI ENDLESS RAP GENERATOR")
print("==============================================")
print("")
print("Type STOP! at any time to stop.")
print("Press ENTER to begin.")
print("")
_ = readLine()
var running = true
while running {
do {
let verse =
try await generateVerse()
print("")
print(verse)
print("")
// Remember the AI's verse
conversation.append([
"role": "assistant",
"content": verse
])
// Tell AI to continue
conversation.append([
"role": "user",
"content":
"Continue the freestyle. Create four completely new rhyming lines."
])
// Check for STOP command
if let input = readLine() {
if input.trimmingCharacters(
in: .whitespacesAndNewlines
).uppercased() == "STOP!" {
running = false
print("")
print("==============================================")
print(" FREESTYLE STOPPED")
print("==============================================")
}
}
} catch {
print("")
print("AI ERROR:")
print(error.localizedDescription)
print("")
// Prevent an infinite error loop
print("Type STOP! to quit or ENTER to retry.")
if let input = readLine(),
input.uppercased() == "STOP!" {
running = false
}
}
}
api.openai.com { "error": { "message": "Missing bearer or basic authentication in header", "type": "invalid_request_error", "param": null, "code": null } }
//That allows incoming WhatsApp messages to be sent to an OpenAI model and the generated response sent back automatically. OpenAI’s current API supports the Responses API and GPT-5.6 Luna, which is optimised for high-volume/cost-sensitive workloads.
//Node.js implementation
import express from "express";
import OpenAI from "openai";
const app = express();
app.use(express.json());
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
const VERIFY_TOKEN = process.env.WHATSAPP_VERIFY_TOKEN;
const WHATSAPP_TOKEN = process.env.WHATSAPP_TOKEN;
const PHONE_NUMBER_ID = process.env.WHATSAPP_PHONE_NUMBER_ID;
// --------------------------------------------------
// WhatsApp webhook verification
// --------------------------------------------------
app.get("/webhook", (req, res) => {
const mode = req.query["hub.mode"];
const token = req.query["hub.verify_token"];
const challenge = req.query["hub.challenge"];
if (mode === "subscribe" && token === VERIFY_TOKEN) {
console.log("WhatsApp webhook verified");
return res.status(200).send(challenge);
}
res.sendStatus(403);
});
// --------------------------------------------------
// Receive WhatsApp messages
// --------------------------------------------------
app.post("/webhook", async (req, res) => {
// Respond immediately to WhatsApp
res.sendStatus(200);
try {
const message =
req.body?.entry?.[0]?.changes?.[0]?.value?.messages?.[0];
if (!message) {
return;
}
// Only process text messages
if (message.type !== "text") {
return;
}
const sender = message.from;
const text = message.text.body;
console.log(
`Message from ${sender}: ${text}`
);
// --------------------------------------------------
// Ask OpenAI
// --------------------------------------------------
const response = await openai.responses.create({
model: "gpt-5.6-luna",
instructions: `
You are an intelligent WhatsApp assistant.
Reply naturally and conversationally.
Your responses should:
- sound human
- be helpful
- understand context
- avoid unnecessary explanations
- use short paragraphs
- ask questions when clarification is needed
- match the user's language
- use emojis occasionally when appropriate
Do not mention that you are an AI unless specifically asked.
`,
input: text
});
const reply = response.output_text;
console.log(
`AI reply: ${reply}`
);
// --------------------------------------------------
// Send reply back to WhatsApp
// --------------------------------------------------
await sendWhatsAppMessage(
sender,
reply
);
} catch (error) {
console.error(
"Processing error:",
error
);
}
});
// --------------------------------------------------
// Send WhatsApp message
// --------------------------------------------------
async function sendWhatsAppMessage(
recipient,
message
) {
const url =
`https://graph.facebook.com/vXX.X/` +
`${PHONE_NUMBER_ID}/messages`;
const response = await fetch(url, {
method: "POST",
headers: {
"Authorization":
`Bearer ${WHATSAPP_TOKEN}`,
"Content-Type":
"application/json"
},
body: JSON.stringify({
messaging_product: "whatsapp",
to: recipient,
type: "text",
text: {
body: message
}
})
});
const data = await response.json();
if (!response.ok) {
console.error(
"WhatsApp API error:",
data
);
throw new Error(
"Failed to send WhatsApp message"
);
}
return data;
}
// --------------------------------------------------
// Start server
// --------------------------------------------------
const PORT =
process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(
`WhatsApp AI server running on port ${PORT}`
);
});
//Camera App to detect what color an item is
import SwiftUI
import AVFoundation
import CoreImage
import CoreImage.CIFilterBuiltins
// MARK: - Color Information
struct DetectedColor {
let name: String
let red: Int
let green: Int
let blue: Int
let hex: String
let confidence: Int
var swiftUIColor: Color {
Color(
red: Double(red) / 255.0,
green: Double(green) / 255.0,
blue: Double(blue) / 255.0
)
}
}
// MARK: - Color Detector
final class ColorDetector: ObservableObject {
var detectedColor = DetectedColor(
name: "Scanning...",
red: 0,
green: 0,
blue: 0,
hex: " #000000",
confidence: 0
)
private let ciContext = CIContext()
func detect(from pixelBuffer: CVPixelBuffer) {
let ciImage = CIImage(cvPixelBuffer: pixelBuffer)
let width = CVPixelBufferGetWidth(pixelBuffer)
let height = CVPixelBufferGetHeight(pixelBuffer)
// Sample a small area around the centre of the camera frame.
let sampleSize: CGFloat = 80
let centerX = CGFloat(width) / 2
let centerY = CGFloat(height) / 2
let sampleRect = CGRect(
x: centerX - sampleSize / 2,
y: centerY - sampleSize / 2,
width: sampleSize,
height: sampleSize
)
guard let averageColor = averageColor(
from: ciImage,
rect: sampleRect
) else {
return
}
let red = Int(averageColor.red * 255)
let green = Int(averageColor.green * 255)
let blue = Int(averageColor.blue * 255)
let result = identifyColor(
red: red,
green: green,
blue: blue
)
DispatchQueue.main.async {
self.detectedColor = result
}
}
private func averageColor(
from image: CIImage,
rect: CGRect
) -> (red: CGFloat, green: CGFloat, blue: CGFloat)? {
let cropped = image.cropped(to: rect)
let filter = CIFilter.areaAverage()
filter.inputImage = cropped
filter.extent = cropped.extent
guard let outputImage = filter.outputImage else {
return nil
}
var pixel = [UInt8](repeating: 0, count: 4)
ciContext.render(
outputImage,
toBitmap: &pixel,
rowBytes: 4,
bounds: CGRect(x: 0, y: 0, width: 1, height: 1),
format: .RGBA8,
colorSpace: CGColorSpaceCreateDeviceRGB()
)
return (
red: CGFloat(pixel[0]) / 255.0,
green: CGFloat(pixel[1]) / 255.0,
blue: CGFloat(pixel[2]) / 255.0
)
}
// MARK: - Colour Classification
private func identifyColor(
red: Int,
green: Int,
blue: Int
) -> DetectedColor {
let r = Double(red) / 255.0
let g = Double(green) / 255.0
let b = Double(blue) / 255.0
let maxValue = max(r, g, b)
let minValue = min(r, g, b)
let brightness = maxValue
let saturation = maxValue == 0
? 0
: (maxValue - minValue) / maxValue
var hue: Double = 0
if maxValue != minValue {
let delta = maxValue - minValue
if maxValue == r {
hue = 60 * ((g - b) / delta)
if hue < 0 {
hue += 360
}
} else if maxValue == g {
hue = 60 * ((b - r) / delta + 2)
} else {
hue = 60 * ((r - g) / delta + 4)
}
}
let name: String
if brightness < 0.12 {
name = "Black"
} else if saturation < 0.12 && brightness > 0.88 {
name = "White"
} else if saturation < 0.15 {
name = "Gray"
} else if hue < 15 || hue >= 345 {
name = brightness < 0.45 ? "Dark Red" : "Red"
} else if hue < 45 {
name = "Orange"
} else if hue < 70 {
name = "Yellow"
} else if hue < 160 {
name = "Green"
} else if hue < 200 {
name = "Cyan"
} else if hue < 250 {
name = "Blue"
} else if hue < 290 {
name = "Purple"
} else if hue < 345 {
name = "Pink"
} else {
name = "Unknown"
}
let hex = String(
format: " #%02X%02X%02X",
red,
green,
blue
)
// Simple confidence estimate based on saturation
// and how strongly the colour falls within its hue range.
let confidence = min(
99,
max(
50,
Int((saturation * 100) + 40)
)
)
return DetectedColor(
name: name,
red: red,
green: green,
blue: blue,
hex: hex,
confidence: confidence
)
}
}
// MARK: - Camera Manager
final class CameraManager: NSObject,
ObservableObject,
AVCaptureVideoDataOutputSampleBufferDelegate {
let session = AVCaptureSession()
private let videoOutput = AVCaptureVideoDataOutput()
private let videoQueue = DispatchQueue(
label: "color.detector.video.queue"
)
var colorDetector: ColorDetector?
func startCamera() {
guard !session.isRunning else {
return
}
session.beginConfiguration()
session.sessionPreset = .photo
guard let camera = AVCaptureDevice.default(
.builtInWideAngleCamera,
for: .video,
position: .back
) else {
print("Rear camera unavailable")
session.commitConfiguration()
return
}
do {
let input = try AVCaptureDeviceInput(device: camera)
if session.canAddInput(input) {
session.addInput(input)
}
videoOutput.videoSettings = [
kCVPixelBufferPixelFormatTypeKey as String:
kCVPixelFormatType_32BGRA
]
videoOutput.alwaysDiscardsLateVideoFrames = true
videoOutput.setSampleBufferDelegate(
self,
queue: videoQueue
)
if session.canAddOutput(videoOutput) {
session.addOutput(videoOutput)
}
if let connection = videoOutput.connection(
with: .video
) {
connection.videoOrientation = .portrait
}
session.commitConfiguration()
videoQueue.async {
self.session.startRunning()
}
} catch {
print("Camera error:", error)
session.commitConfiguration()
}
}
func stopCamera() {
videoQueue.async {
self.session.stopRunning()
}
}
func captureOutput(
_ output: AVCaptureOutput,
didOutput sampleBuffer: CMSampleBuffer,
from connection: AVCaptureConnection
) {
guard let pixelBuffer =
CMSampleBufferGetImageBuffer(sampleBuffer)
else {
return
}
colorDetector?.detect(
from: pixelBuffer
)
}
}
// MARK: - Camera Preview
struct CameraPreview: UIViewRepresentable {
let session: AVCaptureSession
func makeUIView(
context: Context
) -> UIView {
let view = CameraView()
view.session = session
return view
}
func updateUIView(
_ uiView: UIView,
context: Context
) {
}
}
final class CameraView: UIView {
var session: AVCaptureSession? {
didSet {
previewLayer.session = session
}
}
private let previewLayer =
AVCaptureVideoPreviewLayer()
override init(frame: CGRect) {
super.init(frame: frame)
previewLayer.videoGravity =
.resizeAspectFill
layer.addSublayer(previewLayer)
}
required init?(
coder: NSCoder
) {
super.init(coder: coder)
previewLayer.videoGravity =
.resizeAspectFill
layer.addSublayer(previewLayer)
}
override func layoutSubviews() {
super.layoutSubviews()
previewLayer.frame = bounds
}
}
// MARK: - Targeting Circle
struct TargetCircle: View {
var body: some View {
Circle()
.stroke(
Color.white,
style: StrokeStyle(
lineWidth: 3,
dash: [8, 6]
)
)
.frame(
width: 150,
height: 150
)
.shadow(
radius: 5
)
}
}
// MARK: - Main Interface
struct ContentView: View {
private var detector =
ColorDetector()
private var camera =
CameraManager()
var body: some View {
ZStack {
// Camera
CameraPreview(
session: camera.session
)
.ignoresSafeArea()
// Dark overlay
Color.black
.opacity(0.15)
.ignoresSafeArea()
VStack {
// Top title
HStack {
Image(systemName: "camera.viewfinder")
.font(.title2)
Text("Color Detector")
.font(
.system(
size: 22,
weight: .bold
)
)
Spacer()
}
.foregroundStyle(.white)
.padding()
Spacer()
// Target
TargetCircle()
Text("Point at a colour")
.font(
.system(
size: 15,
weight: .medium
)
)
.foregroundStyle(.white)
.padding(.top, 10)
Spacer()
// Information panel
VStack(spacing: 12) {
HStack {
Circle()
.fill(
detector
.detectedColor
.swiftUIColor
)
.frame(
width: 45,
height: 45
)
.overlay(
Circle()
.stroke(
Color.white,
lineWidth: 2
)
)
VStack(
alignment: .leading,
spacing: 2
) {
Text(
detector
.detectedColor
.name
)
.font(
.system(
size: 25,
weight: .bold
)
)
Text(
"Confidence: \(detector.detectedColor.confidence)%"
)
.font(.caption)
.foregroundStyle(.secondary)
}
Spacer()
}
Divider()
HStack {
VStack(
alignment: .leading
) {
Text("RGB")
.font(.caption)
.foregroundStyle(.secondary)
Text(
"\(detector.detectedColor.red), " +
"\(detector.detectedColor.green), " +
"\(detector.detectedColor.blue)"
)
.font(
.system(
size: 17,
weight: .semibold
)
)
}
Spacer()
VStack(
alignment: .trailing
) {
Text("HEX")
.font(.caption)
.foregroundStyle(.secondary)
Text(
detector
.detectedColor
.hex
)
.font(
.system(
size: 17,
weight: .semibold,
design: .monospaced
)
)
}
}
}
.padding()
.background(
.ultraThinMaterial,
in: RoundedRectangle(
cornerRadius: 24
)
)
.padding()
}
}
.onAppear {
camera.colorDetector = detector
AVCaptureDevice.requestAccess(
for: .video
) { granted in
if granted {
DispatchQueue.main.async {
camera.startCamera()
}
}
}
}
.onDisappear {
camera.stopCamera()
}
}
}
// MARK: - App Entry Point
struct ColorDetectorApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
Want this luxury life forever ♾️
05/06/2026