from flask import Blueprint, request, jsonify from collections import Counter import re from util.logger import logger from auth.token import verify_token stringutils_blueprint = Blueprint('stringutils_tool', __name__) @stringutils_blueprint.route('/api/string/analyze', methods=['POST']) def string_analyze(): user = verify_token() if not user: return jsonify({"message": "Nicht autorisiert"}), 401 try: data = request.get_json() or {} text = data.get("text", "") operation = data.get("operation", "stats") if operation == "stats": words = text.split() if text.strip() else [] lines = text.split('\n') return jsonify({ "operation": "stats", "chars": len(text), "chars_no_spaces": len(text.replace(' ', '')), "words": len(words), "lines": len(lines), "spaces": text.count(' '), }) elif operation == "uppercase": return jsonify({"operation": "uppercase", "result": text.upper()}) elif operation == "lowercase": return jsonify({"operation": "lowercase", "result": text.lower()}) elif operation == "titlecase": return jsonify({"operation": "titlecase", "result": text.title()}) elif operation == "reverse": return jsonify({"operation": "reverse", "result": text[::-1]}) elif operation == "trim": return jsonify({"operation": "trim", "result": text.strip()}) elif operation == "remove_spaces": return jsonify({"operation": "remove_spaces", "result": text.replace(' ', '')}) elif operation == "count_words": words = re.findall(r'\b\w+\b', text.lower()) counter = Counter(words) top10 = [{"word": w, "count": c} for w, c in counter.most_common(10)] return jsonify({"operation": "count_words", "words": top10}) else: return jsonify({"message": "Unbekannte Operation"}), 400 except Exception as e: logger.error(f"Fehler stringutils: {e}") return jsonify({"message": "Fehler bei der Verarbeitung"}), 500