montaser14/correction
0
1from flask import Flask, request, jsonify2import PyPDF23import os4import re5import requests6from flask_cors import CORS7 8app = Flask(__name__)9# CORS(app, resources={r"/*": {"origins": "*"}})10#CORS(app, resources={r"/*": {"origins": "*"}}, allow_headers=["Content-Type"], supports_credentials=True)11# CORS(app, resources={r"/*": {"origins": "*"}}, allow_headers=["Content-Type", "Authorization"], supports_credentials=True)12CORS(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True)13 14 15def extract_text_from_pdf(pdf_file):16 """ استخراج النص من PDF """17 try:18 pdf_reader = PyPDF2.PdfReader(pdf_file)19 text = ""20 for page in pdf_reader.pages:21 text += page.extract_text() + "\n"22 return text.strip()23 except Exception as e:24 return str(e)25 26@app.route('/')27def home():28 return jsonify({"message": "Grammar Correction API is running! Use /correct endpoint."})29 30@app.route('/correct', methods=['OPTIONS'])31def handle_preflight():32 """Handles CORS preflight requests."""33 response = jsonify({"message": "Preflight request successful"})34 response.headers.add("Access-Control-Allow-Origin", "*")35 response.headers.add("Access-Control-Allow-Methods", "GET, POST, OPTIONS")36 response.headers.add("Access-Control-Allow-Headers", "Content-Type, Authorization")37 response.headers.add("Access-Control-Allow-Credentials", "true")38 return response39 40@app.route('/correct', methods=['POST'])41def correct():42 try:43 # التحقق مما إذا كان الإدخال نصيًا أو ملف PDF44 if 'file' in request.files:45 pdf_file = request.files['file']46 text = extract_text_from_pdf(pdf_file)47 else:48 data = request.get_json()49 if 'text' not in data or not isinstance(data['text'], str):50 return jsonify({'error': 'Invalid input, provide a text string or a PDF file'}), 40051 text = data['text'].strip()52 53 url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=AIzaSyBiBhRm3u-7JXGNWvPSV3_eG1EbLm5q_P4"54 55 # ترويسة الطلب56 headers = {"Content-Type": "application/json"}57 58 data = {59 "contents": [60 {61 "parts": [62 # {"text": "You are an advanced AI specialized in Arabic and English grammar correction, Correct the following Arabic and English text and return ONLY a valid JSON object with these keys:'corrected_text', 'spelling_errors', 'grammar_errors', 'punctuation_errors', 'style_readability_issues'. Do NOT return any example text. Ensure strict JSON formatting. No explanations, no extra text."},63 {"text": "Correct the following text and then return only the corrected text followed by a JSON object with these keys: spelling_errors, grammar_errors, punctuation_errors, semantic_contextual_errors, and style_readability_issues. and values should be numerical, Do not include any additional explanations or text."},64 {"text": f"{text}"}65 ]66 }67 ]68 }69 70 # إرسال الطلب71 response = requests.post(url, json=data, headers=headers)72 73 # معالجة الاستجابة74 if response.status_code == 200:75 try:76 response_json = response.json()77 text = response_json.get("candidates", [{}])[0].get("content", {}).get("parts", [{}])[0].get("text", "")78 79 corrected_text=""80 c = True81 for w in text.split():82 if w == "```json":83 corrected_text = corrected_text.rstrip()84 break85 corrected_text+=w 86 corrected_text+=" "87 88 if 'file' in request.files:89 l = ""90 p = False91 for w in text.split():92 if w == "```json":93 p = True94 continue95 if w == "```":96 break 97 if p: 98 l += w99 numbers = re.findall(r'\d+', l)100 indexes = ['spelling_errors', 'grammar_errors', 'punctuation_errors', 'semantic_contextual_errors', 'style_readability_issues']101 error_type = dict(zip(indexes, numbers))102 103 104 # return jsonify({105 # 'corrected_text': corrected_text,106 # 'error_type': error_type,107 # })108 109 response = jsonify({110 'corrected_text': corrected_text,111 'error_type': error_type,112 })113 response.headers.add("Access-Control-Allow-Origin", "*")114 response.headers.add("Access-Control-Allow-Methods", "GET, POST, OPTIONS")115 response.headers.add("Access-Control-Allow-Headers", "Content-Type, Authorization")116 response.headers.add("Access-Control-Allow-Credentials", "true")117 return response118 119 else:120 # return jsonify({'corrected_text': corrected_text})121 122 response = jsonify({123 'corrected_text': corrected_text,124 })125 response.headers.add("Access-Control-Allow-Origin", "*")126 response.headers.add("Access-Control-Allow-Methods", "GET, POST, OPTIONS")127 response.headers.add("Access-Control-Allow-Headers", "Content-Type, Authorization")128 response.headers.add("Access-Control-Allow-Credentials", "true")129 return response130 131 except Exception as e:132 # return jsonify({'error': str(e)}), 500 133 response = jsonify({'error': str(e)})134 response.headers.add("Access-Control-Allow-Origin", "*")135 response.headers.add("Access-Control-Allow-Methods", "GET, POST, OPTIONS")136 response.headers.add("Access-Control-Allow-Headers", "Content-Type, Authorization")137 response.headers.add("Access-Control-Allow-Credentials", "true")138 return response139 140 else:141 return jsonify({'error': f"خطأ {response.status_code}: {response.text}"}), 500142 143 except Exception as e:144 return jsonify({'error': str(e)}), 500 145 146if __name__ == '__main__':147 app.run(port=7860,host="0.0.0.0")148 