commit fe29795f65eeffd1a6428deaea4466df962bceb0
parent e3d9a093151c06f2520944fa25cabf503d2148e5
Author: AMIT DUTTA <amitdutta4255@gmail.com>
Date: Tue, 27 Jan 2026 20:58:52 +0530
Enhance CORS support and update API routes
Diffstat:
| M | backend.py | | | 65 | ++++++++++++++++++++--------------------------------------------- |
1 file changed, 20 insertions(+), 45 deletions(-)
diff --git a/backend.py b/backend.py
@@ -3,18 +3,18 @@ from flask_cors import CORS
import re
app = Flask(__name__)
-CORS(app)
+# Allow CORS for all domains so your frontend works everywhere
+CORS(app, resources={r"/api/*": {"origins": "*"}})
@app.route('/')
def home():
- return "Emojic Compiler API is Running!"
+ return "Emojic Compiler API is Running! (v1.1)"
-@app.route('/api/compile', methods=['POST'])
+@app.route('/api/compile', methods=['POST', 'OPTIONS'])
def compile_emojic():
- """
- Transpiles Emojic -> C
- This parses the #define macros present in the source code itself.
- """
+ if request.method == 'OPTIONS':
+ return jsonify({}), 200
+
data = request.json
source_code = data.get('code', '')
@@ -22,31 +22,24 @@ def compile_emojic():
return jsonify({"error": "No code provided"}), 400
mapping = {}
- # Regex to find #define EMOJI REPLACEMENT
define_pattern = re.compile(r'#define\s+(\S+)\s+(.+)')
lines = source_code.splitlines()
code_lines = []
- # Pass 1: Extract mappings and separate code
for line in lines:
match = define_pattern.match(line.strip())
if match:
- # group(1) is the Emoji, group(2) is the C replacement
mapping[match.group(1)] = match.group(2).strip()
else:
code_lines.append(line)
translated_code = "\n".join(code_lines)
-
- # Sort keys by length descending to prevent partial replacements
sorted_keys = sorted(mapping.keys(), key=len, reverse=True)
- # Pass 2: Replace emojis with C code
for key in sorted_keys:
translated_code = translated_code.replace(key, mapping[key])
- # Ensure standard header is present if logic needs it
header = "#include <stdio.h>\n"
if "#include" not in translated_code and "printf" in translated_code:
translated_code = header + translated_code
@@ -57,36 +50,28 @@ def compile_emojic():
"message": "Transpilation successful."
})
-@app.route('/api/analyze', methods=['POST'])
+@app.route('/api/analyze', methods=['POST', 'OPTIONS'])
def analyze_code():
- """
- Scans C code and returns a list of tokens (keywords, symbols)
- that are candidates for Emojification.
- """
+ if request.method == 'OPTIONS':
+ return jsonify({}), 200
+
data = request.json
c_code = data.get('code', '')
if not c_code:
return jsonify({"error": "No code provided"}), 400
- # Define what we consider "interesting" tokens
- # 1. Keywords
keywords_regex = r'\b(int|float|char|double|void|return|if|else|while|for|main|printf|scanf|include|define|struct)\b'
- # 2. Common Operators/Symbols
- symbols_regex = r'([\{\}\(\)\;\"\#\<\>])' # Captures { } ( ) ; " # < >
+ symbols_regex = r'([\{\}\(\)\;\"\#\<\>])'
found_tokens = set()
- # Find keywords
for match in re.finditer(keywords_regex, c_code):
found_tokens.add(match.group(1))
- # Find symbols
for match in re.finditer(symbols_regex, c_code):
found_tokens.add(match.group(1))
- # Sort them for neat display (longer first usually looks better for mapping, or alphabetical)
- # Here we just sort alphabetically for the UI list
sorted_tokens = sorted(list(found_tokens))
return jsonify({
@@ -94,42 +79,32 @@ def analyze_code():
"tokens": sorted_tokens
})
-@app.route('/api/transform', methods=['POST'])
+@app.route('/api/transform', methods=['POST', 'OPTIONS'])
def transform_to_emojic():
- """
- Transforms C -> Emojic using a User-Provided Mapping.
- """
+ if request.method == 'OPTIONS':
+ return jsonify({}), 200
+
data = request.json
c_code = data.get('code', '')
- user_map = data.get('mapping', {}) # Expects { "int": "😒", ... }
+ user_map = data.get('mapping', {})
if not c_code:
return jsonify({"error": "No code provided"}), 400
- if not user_map:
- return jsonify({"error": "No mapping provided"}), 400
- # Generate the #define block
- # Note: user_map is { "C_Token": "Emoji" }
header_block = ""
-
- # Filter out empty mappings
active_map = {k: v for k, v in user_map.items() if v and v.strip()}
for c_key, emoji_val in active_map.items():
- # Skip special handling for now, just direct defines
- if c_key == "#": continue # defines for # are tricky
+ if c_key == "#": continue
header_block += f"#define {emoji_val} {c_key}\n"
header_block += "\n"
- # Sort by length of C keyword to avoid replacing substrings incorrectly
sorted_c_keys = sorted(active_map.keys(), key=len, reverse=True)
transformed_body = c_code
for c_key in sorted_c_keys:
- # Use regex to replace only whole words if it's a word, or literal if it's a symbol
if c_key.isalnum():
- # \b matches word boundary
pattern = r'\b' + re.escape(c_key) + r'\b'
transformed_body = re.sub(pattern, active_map[c_key], transformed_body)
else:
@@ -142,5 +117,5 @@ def transform_to_emojic():
"emojic_code": final_output
})
-if __name__ == '__main__':
- app.run(debug=True, port=5000)
+# This is important for Vercel
+app = app