File size: 3,505 Bytes
9a4cd9f
 
78625af
9a4cd9f
78625af
 
 
9a4cd9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67b09bb
 
 
 
 
 
 
 
9a4cd9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51c5501
dbeedd3
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
import os

# Set cache dirs (must match Dockerfile env vars)
os.environ['HOME'] = '/app'
os.environ['HF_HOME'] = '/app/.hf_cache'
os.environ['LANGTOOL_HOME'] = '/app/.ltool_cache'
os.environ['XDG_CACHE_HOME'] = '/app/.cache'


from flask import Flask, request, jsonify
from paragraph_checker import ParagraphCorrector
from grammar_chatbot import GrammarChatbot
import logging

app = Flask(__name__)

# Initialize services
paragraph_service = ParagraphCorrector()
chatbot_service = GrammarChatbot()

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

@app.route('/', methods=['GET'])
def home():
    return '''
    <h2>πŸ“ Convomate Module</h2>
    <p>Use POST <code>/correct_text</code> or <code>/chat</code> endpoints.</p>
    <p>GET <code>/health</code> for health check.</p>
    '''

@app.route('/correct_text', methods=['POST'])
def handle_paragraph():
    """Endpoint for conservative paragraph correction"""
    data = request.get_json()
    text = data.get('paragraph', '').strip()

    if not text:
        return jsonify({"error": "No paragraph provided"}), 400

    try:
        corrected = paragraph_service.conservative_correction(text)
        return jsonify({
            "original_text": text,
            "grammar_corrected": corrected
        })
    except Exception as e:
        logger.error(f"Paragraph correction error: {str(e)}")
        return jsonify({
            "error": "Paragraph processing failed",
            "details": str(e)
        }), 500

@app.route('/chat', methods=['POST', 'GET'])  # Added GET method for testing
def handle_chat():
    """Endpoint for fluent conversational correction"""
    if request.method == 'POST':
        data = request.get_json()
        user_input = data.get('message', '').strip()
    else:  # GET method for testing
        user_input = request.args.get('message', '').strip()

    if not user_input:
        return jsonify({"error": "No message provided"}), 400

    try:
        response = chatbot_service.generate_response(user_input)
        return jsonify({
            "original_text": response["original_text"],
            "corrected_text": response["corrected_text"],
            "is_corrected": response["is_corrected"],
            "compliment": response["compliment"],
            "next_question": response["next_question"],
            "end_conversation": response["end_conversation"]
        })
    except Exception as e:
        logger.error(f"Chatbot error: {str(e)}")
        return jsonify({
            "error": "Chat processing failed",
            "details": str(e)
        }), 500

@app.route('/start', methods=['GET'])
def start_conversation():
    try:
        response = chatbot_service.start_conversation()
        return jsonify(response)
    except Exception as e:
        logger.error(f"Start conversation error: {str(e)}")
        return jsonify({
            "error": "Failed to start conversation",
            "details": str(e)
        }), 500

@app.route('/health', methods=['GET', 'POST'])  # Added POST method for testing
def health_check():
    return jsonify({
        "status": "healthy",
        "services": ["paragraph", "chat"],
        "details": {
            "paragraph_service": "active",
            "chatbot_service": "active"
        }
    })

if __name__ == '__main__':
    logger.info("Starting grammar services...")
    port = int(os.environ.get("PORT", 8080))  # Default fallback port
    app.run(host='0.0.0.0', port=port, debug=True)