id-auto-formalizer
Version:
Konversi teks Bahasa Indonesia dari kasual ke formal untuk surat, email, dan laporan resmi
364 lines (307 loc) ⢠11 kB
JavaScript
const IndonesianFormalizer = require('../src/index');
// ============================================
// 1. Express.js Middleware
// ============================================
const express = require('express');
const app = express();
app.use(express.json());
// Middleware untuk auto-formalisasi
const formalizerMiddleware = (req, res, next) => {
if (req.body && req.body.text) {
const formalizer = new IndonesianFormalizer();
req.body.originalText = req.body.text;
req.body.text = formalizer.formalize(req.body.text);
req.body.formalityAnalysis = formalizer.analyzeFormalityLevel(req.body.originalText);
}
next();
};
// Endpoint contoh
app.post('/api/formalize', formalizerMiddleware, (req, res) => {
res.json({
original: req.body.originalText,
formalized: req.body.text,
analysis: req.body.formalityAnalysis
});
});
// ============================================
// 2. Discord Bot Integration
// ============================================
const Discord = require('discord.js');
const client = new Discord.Client();
const formalizer = new IndonesianFormalizer();
client.on('message', message => {
// Command: !formalize [text]
if (message.content.startsWith('!formalize')) {
const text = message.content.slice(11);
const formal = formalizer.formalize(text);
const analysis = formalizer.analyzeFormalityLevel(text);
const embed = new Discord.MessageEmbed()
.setTitle('š®š© Text Formalized')
.addField('Original', text)
.addField('Formal', formal)
.addField('Formality Score', `${analysis.score}% (${analysis.level})`)
.setColor('#0099ff');
message.channel.send(embed);
}
// Auto-formalize untuk channel tertentu
if (message.channel.name === 'formal-only' && !message.author.bot) {
const analysis = formalizer.analyzeFormalityLevel(message.content);
if (analysis.score < 70) {
const formal = formalizer.formalize(message.content);
message.reply(`Mohon gunakan bahasa formal. Mungkin maksud Anda: "${formal}"`);
}
}
});
// ============================================
// 3. Telegram Bot Integration
// ============================================
const TelegramBot = require('node-telegram-bot-api');
const bot = new TelegramBot('YOUR_TOKEN', { polling: true });
// Command handler
bot.onText(/\/formalize (.+)/, (msg, match) => {
const chatId = msg.chat.id;
const text = match[1];
const formal = formalizer.formalize(text);
const analysis = formalizer.analyzeFormalityLevel(text);
const response = `
š *Original:* ${text}
⨠*Formal:* ${formal}
š *Formality:* ${analysis.score}% (${analysis.level})
`;
bot.sendMessage(chatId, response, { parse_mode: 'Markdown' });
});
// Inline query untuk real-time formalization
bot.on('inline_query', query => {
const text = query.query;
if (!text) return;
const formal = formalizer.formalize(text);
const results = [{
type: 'article',
id: '1',
title: 'Formalized Text',
description: formal,
input_message_content: {
message_text: formal
}
}];
bot.answerInlineQuery(query.id, results);
});
// ============================================
// 4. Email Processing (dengan Nodemailer)
// ============================================
const nodemailer = require('nodemailer');
async function sendFormalEmail(to, subject, casualBody) {
const formalBody = formalizer.formalize(casualBody);
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your-email@gmail.com',
pass: 'your-password'
}
});
const mailOptions = {
from: 'your-email@gmail.com',
to: to,
subject: formalizer.formalize(subject),
html: `
<div style="font-family: Arial, sans-serif;">
<p>${formalBody}</p>
<hr>
<small style="color: #666;">
Pesan ini telah diformalisasi secara otomatis.
Original: "${casualBody}"
</small>
</div>
`
};
return transporter.sendMail(mailOptions);
}
// ============================================
// 5. VS Code Extension Mock
// ============================================
const vscode = {
// Mock VS Code API
commands: {
registerCommand: (command, callback) => {
console.log(`Registered command: ${command}`);
}
},
window: {
showInformationMessage: msg => console.log(`Info: ${msg}`),
activeTextEditor: {
document: { getText: () => 'mock text' },
edit: editBuilder => { }
}
}
};
// Command: Formalize Selection
vscode.commands.registerCommand('indonesian-formalizer.formalizeSelection', () => {
const editor = vscode.window.activeTextEditor;
if (!editor) return;
const selection = editor.selection;
const text = editor.document.getText(selection);
const formal = formalizer.formalize(text);
editor.edit(editBuilder => {
editBuilder.replace(selection, formal);
});
// eslint-disable-next-line no-undef
vscode.window.showInformationMessage(`Text formalized! Score: ${analysis.score}%`);
});
// ============================================
// 6. React Component
// ============================================
const React = require('react');
const FormalizerComponent = () => {
const [text, setText] = React.useState('');
const [formal, setFormal] = React.useState('');
const [analysis, setAnalysis] = React.useState(null);
const handleFormalize = () => {
const formalizer = new IndonesianFormalizer();
const result = formalizer.formalize(text);
const analysisResult = formalizer.analyzeFormalityLevel(text);
setFormal(result);
setAnalysis(analysisResult);
};
return React.createElement('div', { className: 'formalizer' },
React.createElement('h2', null, 'š®š© Indonesian Text Formalizer'),
React.createElement('textarea', {
value: text,
onChange: e => setText(e.target.value),
placeholder: 'Ketik teks informal di sini...'
}),
React.createElement('button', { onClick: handleFormalize }, 'Formalize'),
formal && React.createElement('div', { className: 'result' },
React.createElement('h3', null, 'Hasil Formal:'),
React.createElement('p', null, formal),
analysis && React.createElement('div', { className: 'analysis' },
React.createElement('span', null, `Skor: ${analysis.score}%`),
React.createElement('span', null, `Level: ${analysis.level}`)
)
)
);
};
// ============================================
// 7. CLI Tool untuk Git Commit Messages
// ============================================
const { execSync } = require('child_process');
function formalizeGitCommit() {
// Get staged files
const staged = execSync('git diff --cached --name-only').toString().trim();
if (!staged) {
console.log('No staged files');
return;
}
// Get commit message from user
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
readline.question('Commit message (informal): ', casualMessage => {
const formalMessage = formalizer.formalize(casualMessage);
console.log(`\nOriginal: ${casualMessage}`);
console.log(`Formal: ${formalMessage}`);
readline.question('\nUse formal version? (y/n): ', answer => {
const message = answer.toLowerCase() === 'y' ? formalMessage : casualMessage;
try {
execSync(`git commit -m "${message}"`);
console.log('ā
Commit successful!');
} catch (error) {
console.error('ā Commit failed:', error.message);
}
readline.close();
});
});
}
// ============================================
// 8. Slack Bot Integration
// ============================================
const { WebClient } = require('@slack/web-api');
const slackClient = new WebClient('YOUR_SLACK_TOKEN');
async function handleSlackMessage(event) {
// Slash command: /formalize [text]
if (event.command === '/formalize') {
const text = event.text;
const formal = formalizer.formalize(text);
const analysis = formalizer.analyzeFormalityLevel(text);
const blocks = [
{
type: 'section',
text: {
type: 'mrkdwn',
// eslint-disable-next-line max-len
text: `*Original:* ${text}\n*Formal:* ${formal}\n*Formality Score:* ${analysis.score}% (${analysis.level})`
}
}
];
return {
response_type: 'in_channel',
blocks: blocks
};
}
}
// ============================================
// 9. Browser Extension Content Script
// ============================================
const browserExtension = {
// Fungsi untuk browser extension
formalizeTextarea: function () {
// eslint-disable-next-line no-undef
const textareas = document.querySelectorAll('textarea');
textareas.forEach(textarea => {
// Add formalize button
// eslint-disable-next-line no-undef
const button = document.createElement('button');
button.textContent = 'Formalize';
button.style.cssText = 'position: absolute; right: 5px; top: 5px; z-index: 1000;';
button.addEventListener('click', () => {
const formalizer = new IndonesianFormalizer();
const formal = formalizer.formalize(textarea.value);
// eslint-disable-next-line max-len, no-undef
if (confirm(`Replace with formal version?\n\nOriginal: ${textarea.value}\n\nFormal: ${formal}`)) {
textarea.value = formal;
textarea.dispatchEvent(new Event('input', { bubbles: true }));
}
});
// Position button relative to textarea
// eslint-disable-next-line no-undef
const wrapper = document.createElement('div');
wrapper.style.position = 'relative';
textarea.parentNode.insertBefore(wrapper, textarea);
wrapper.appendChild(textarea);
wrapper.appendChild(button);
});
}
};
// ============================================
// 10. WhatsApp Business API Integration
// ============================================
async function handleWhatsAppMessage(message) {
const { from, body } = message;
// Auto-formalize untuk business account
if (body.startsWith('!formal')) {
const text = body.slice(8);
const formal = formalizer.formalize(text);
const analysis = formalizer.analyzeFormalityLevel(text);
const response = `
*Teks Formal:*
${formal}
_Skor formalitas: ${analysis.score}% (${analysis.level})_
`;
// Send response via WhatsApp API
await handleWhatsAppMessage(from, response);
}
}
// Export all integrations
module.exports = {
express: { app, formalizerMiddleware },
discord: { client },
telegram: { bot },
email: { sendFormalEmail },
vscode: { vscode },
react: { FormalizerComponent },
git: { formalizeGitCommit },
slack: { handleSlackMessage },
browser: { browserExtension },
whatsapp: { handleWhatsAppMessage }
};
console.log('š Integration examples loaded! Check the code for implementation details.');