-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathweb_app.py
More file actions
125 lines (104 loc) · 3.72 KB
/
web_app.py
File metadata and controls
125 lines (104 loc) · 3.72 KB
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
#!/usr/bin/env python3
"""
RFC to FOL Web Interface
Provides a web interface for the RFC to FOL converter.
"""
import os
import json
from flask import Flask, request, jsonify, render_template, send_from_directory
from flask_cors import CORS
from dotenv import load_dotenv
from src.llm import HFLLMConverter
# Load environment variables
load_dotenv()
app = Flask(__name__, static_folder='web/static', template_folder='web/templates')
CORS(app) # Enable CORS for all routes
# Initialize the converter once for reuse
converter = None
try:
# Use token from env variable or fall back to default
hf_token = os.getenv("HUGGINGFACE_TOKEN", "key")
model_name = os.getenv("DEFAULT_MODEL", "mistralai/Mixtral-8x7B-Instruct-v0.1")
converter = HFLLMConverter(hf_token=hf_token, model_name=model_name)
except Exception as e:
print(f"Error initializing converter: {str(e)}")
@app.route('/')
def index():
"""Serve the main page"""
return render_template('index.html')
@app.route('/convert', methods=['POST'])
def convert():
"""API endpoint to convert RFC text to formal logic"""
if not converter:
return jsonify({
'success': False,
'error': 'Converter not initialized'
}), 500
data = request.json
rfc_text = data.get('rfc_text', '')
output_format = data.get('output_format', 'FOL').upper()
model_name = data.get('model', converter.client.model)
if not rfc_text:
return jsonify({
'success': False,
'error': 'RFC text is required'
}), 400
try:
# Update model if needed
if model_name != converter.client.model:
converter.client.model = model_name
# Set output format
converter.set_output_format(output_format)
# Convert RFC text to formal logic
result = converter.extract_fol(rfc_text)
# Generate explanation for FOL
explanation = {}
if output_format == 'FOL':
try:
explanation = extract_explanation(result)
except Exception as e:
explanation = {"error": f"Failed to generate explanation: {str(e)}"}
return jsonify({
'success': True,
'rfc_text': rfc_text,
'result': result,
'format': output_format,
'model': model_name,
'explanation': explanation
})
except Exception as e:
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/available_models', methods=['GET'])
def available_models():
"""Return the list of available models"""
return jsonify({
'models': HFLLMConverter.available_models()
})
def extract_explanation(fol):
"""Extract explanation components from FOL formula"""
explanation = {}
# Check if we have quantifiers
if fol.startswith("∀") or fol.startswith("∃"):
# Split by implication
if "→" in fol:
parts = fol.split("→")
explanation["conditions"] = parts[0].strip()
explanation["actions"] = parts[1].strip()
# Identify variables
import re
vars = []
quantifier_pattern = r'[∀∃]([a-z])'
for match in re.finditer(quantifier_pattern, fol):
var = match.group(1)
if var not in vars:
vars.append(var)
explanation["variables"] = vars
return explanation
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
from waitress import serve
print(f"Server is running on http://localhost:{port}")
serve(app, host='0.0.0.0', port=port)