import firebase_admin
from firebase_admin import credentials, firestore, storage
import bcrypt
import os, base64
from app.services.translate import translate_text_with_model
from app.services.tts import text_to_mp3
from dash import html
import html as html_std
from datetime import datetime
from openai import OpenAI
import asyncio
import aiohttp
from app.services.complete import Complete
from app.services.exam_set import prob_i, generate_prob
from google.cloud import vision
from PIL import Image
vision_client = vision.ImageAnnotatorClient()

# Instantiate the class that has the 'prompt' method
cmp = Complete()

client = OpenAI(
  organization=os.environ['OPENAI_ORG'],
)

# Initialize Firebase Admin SDK
firebase_credential = os.environ['GOOGLE_APPLICATION_CREDENTIALS']
cred = credentials.Certificate(firebase_credential)
firebase_admin.initialize_app(cred, {
    'storageBucket': 'lumineum'
})

# Initialize Firestore client
db = firestore.client()

def hash_password(password):
    password_bytes = password.encode('utf-8')
    salt = bcrypt.gensalt()
    hashed_password = bcrypt.hashpw(password_bytes, salt)
    return hashed_password.decode('utf-8')

# Function to add a new user
def add_user(email, password, is_student=True, name=''):
    hashed_password = hash_password(password)
    user_data = {'email': email, 'password': hashed_password, 'is_student': is_student, 'name': name}
    user_ref = db.collection('users').document(email)
    user_ref.set(user_data)
    return True

# Function to check user credentials
def check_user(email, password):
    user_ref = db.collection('users').document(email)
    user_doc = user_ref.get()
    if user_doc.exists:
        user_data = user_doc.to_dict()
        stored_password = user_data['password'].encode('utf-8')  # Stored hashed password
        if bcrypt.checkpw(password.encode('utf-8'), stored_password):
            return True
    return False

# Function to get user by email
def get_user_by_email(email):
    user_ref = db.collection('users').document(email)
    user_doc = user_ref.get()
    if user_doc.exists:
        return user_doc.to_dict()
    return None

# Function to get all users
def get_all_users():
    users = []
    users_ref = db.collection('users')
    for user_doc in users_ref.stream():
        users.append(user_doc.to_dict())
    return users

# Initial text function
def initial_text_():
    return '''KNS Education ardently pursues knowledge and success through genuine education. This institution strives to establish a solid educational foundation, enabling individuals from elementary students to university aspirants to exert their utmost efforts towards their goals. As KNS Education, we have achieved our standing as a premier English education institution through the dedication of exceptional instructors, diligent students, and the support of engaged parents. Rather than resting on our past achievements, we embrace open communication and continue to foster growth.
We pledge to creatively adapt to the evolving landscape of education, guiding an active educational service culture that serves both students and parents to the best of our abilities. KNS Education is at the forefront of incorporating advanced education software technologies, including artificial intelligence, to lead the way in shaping the future of education.
'''

def initial_text():
    return '''This web service is an attempt to use early artificial general intelligence (AGI) in education. The use of AI in education has mainly relied on recommendation systems, such as suggesting English problems suited to the learner's progress. In such cases, it does not matter whether the AI understands English or not. However, this service not only understands English like a human but also uses the instruction-fulfillment ability and the ability for logic of early AGI through a large language model (LLM) interface. It includes the ability to create problems tailored to the learner's situation and the exams they aim to take, just as a human would.
At the current stage, human educators are needed to verify the quality and appropriateness of AI-generated content. However, AI can also assist educators in another way—by providing an initial format for the problems they intend to create, significantly reducing the effort required to craft them. Furthermore, as AI continues to advance and its learning progresses, the problems generated by AI will increasingly reach a level where human educators no longer need to make modifications.
'''

def initial_ocr_text():
    return '''Yesterday, me and my friend was planning to go to the park, but it was raining so hard. I didn't knew that the weather could change so quickly. We decided to stay at home and watch a movie, but my friend sayed she forgot to bring the DVDs. There is many books in my room, so I suggested her to reading one of them instead. She doesn't likes reading much, so she just scrolled through her phone. After some time, I bringed us some snacks, but she said she don't wants to eat anything. While we was talking, my mom entered the room and asked, "Did you finished your homework?" I haven't did it yet because I thought we were going to the park. My mom said, "You should completes your work before playing next time." I promised her that I will finishes it right after my friend leaves.
After my friend left, I decided to play baseball with some kids from the neighborhood. I didn't knew they had already started the game, so I joined late. While we was playing, one of the boys asked, "Do you know how to play the piano?" I said, "No, but my friend plays it very well." After the game, I remembered that I forgot my notebook at school. I told the group, "I need to go to school to get my stuff." When I reached school, the janitor didn't let me in because it was too late. I thought to myself, "I should've checked earlier instead of waiting till now."
'''

async def generate_prob(org_num, prompt, txt, index_n=0, temperature=0.4):
    try:
        model = 'gpt-4o' #'ft:gpt-4o-mini-2024-07-18:lumineum::9pHP6n4n'
        org_key = os.environ[f'OPENAI_ORG{org_num}']
        async with aiohttp.ClientSession() as session:
            async with session.post(
                "https://api.openai.com/v1/chat/completions",
                headers={
                    "Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
                    "OpenAI-Organization": org_key,
                },
                json={
                    "model": model,
                    "messages": [
                        {
                            'role': 'system',
                            'content': '''
You are tasked with creating an English exam problem suitable for a Korean high school English class or Suneung.
Since this is an English exam for Korean students, the instructions should be in Korean, and the passages should be in English.
Provide the response in text without any formatting. Only include the requested information without additional commentary. Do not add bold or italic formatting, but retain any underlining denoted by '___'.
Use Korean 반말(authoritative and direct language) in exam questions and authoritative explanations, rather than 경어(polite language).
'''
                        },
                        {
                            'role': 'user',
                            'content': f'''{prompt}\n{txt}'''
                        },
                    ],
                    "max_tokens": 4096,
                    "temperature": temperature,
                }
            ) as response:
                result = await response.json()
                initial_problem = result['choices'][0]['message']['content']

            return initial_problem, index_n
    except Exception as e:
        return str(e), index_n

# MCQ form function
def mcq_form():
    return '''In this form:
"Q1: Wh
(a)
(b)
(c)
(d)
A: ( )
E:

Q2: Wh
(a)
(b)
(c)
(d)
A: ( )
E:

Q3: Wh
(a)
(b)
(c)
(d)
A: ( )
E:

Q4: Wh
(a)
(b)
(c)
(d)
A: ( )
E:

"

Q1 is about vocabulary, Q2 grammar, Q3 main idea, Q4 inference. Only enclose the answers for Q1, Q2, A3, and A4 up to the enclosed numbers in parentheses, omitting the content of the numbers. For example, refrain from writing 'A: (c) Premier English education' and instead write 'A: (c)'.

You are required to provide the answer in section A: ( ) and the explanation in section E:. Ensure there are no repeated line breaks between the line starting with (d) and the line starting with A:.
'''

# Function to generate MCQs
def generate_mcq(text, prompt, n=4):
    completions = client.completions.create(
        model='gpt-3.5-turbo-instruct',
        prompt=f'From:\n{text}\nGenerate {n} MCQs under the Constraints:\n{prompt}',
        max_tokens=1024,
        stop=None,
        temperature=0.4
    )
    message = completions.choices[0].text
    return message

# Function to generate image
def generate_image(text):
    completion = client.chat.completions.create(
        model='gpt-4o',
        # messages=[{'role': 'user', 'content': f'Create a detailed prompt for DALL-E 3 image generation based on the following text:\n\nText: {text}\n\nThe prompt must include:\n- Depiction of people as clean, elegant, and beautiful, with photorealistic detail\n- A realistic scenario that captures the essence of the text\n- Human actions and gestures that convey appropriate emotions\n- A peaceful, happy, and beautiful atmosphere, unless otherwise specified'}],
        messages=[{'role': 'user', 'content': f"Create an image featuring a small group of young adults with clear, healthy, fair skin and balanced, natural beauty. The individuals should appear of Korean descent, with idealized yet harmonious features that blend subtle Eastern and Western aesthetics. Focus on well-defined facial features (eyes, nose, mouth). For women, clothing should reflect trendy, casual K-POP fashion, with skirts that reveal thighs, and occasionally crop tops. Men and women should wear modern, Western-style clothing. Include natural, balanced lighting in a middle-class setting. The scene should feel intimate, with genuine, subtle expressions that match the context, and no forced poses or exaggerated emotions. The image should look like a high-quality photograph with true-to-life colors and natural clarity, with attention to symmetry and proportion."}],
        max_tokens=500
    )
    prompt = completion.choices[0].message.content
    # Generate the image using DALL-E 3
    response = client.images.generate(
        model='dall-e-3',
        prompt=prompt,
        n=1,
        size='1024x1024',
        quality='standard',
        response_format='b64_json'
    )
    image = [image.b64_json for image in response.data]
    return image

# Function to correct English text
def en_correct(value):
    response = client.chat.completions.create(
        model='gpt-4o',
        messages=[{'role': 'user', 'content': f'''Focus exclusively on the text I have provided. The text below was written with the intention of creating English exam problems, and as such, it may contain various errors. These could include underlines, blanks, circled numbers, incorrect words or expressions, sentences that are contextually misplaced or arranged improperly, or content that doesn't fit. Revise this content into a correct and natural original text without attempting to engage in dialogue or providing explanations before the revised text. If it contains a language other than English, translate it into English. Do not add extra line breaks or additional spacing between lines that were not present in the original text. Also, do not remove line breaks or additional spacing that were present in the original text. When two sentences are separated by a single line break and when they are separated by two line breaks, make sure to distinguish between the two cases. Be careful not to separate paragraphs with two line breaks when the original text uses only a single line break. Simply return the corrected text:\n\n{value}'''}],
        max_tokens=3072
    )
    return response.choices[0].message.content
    
# Function to simplify English text
def en_simplify(value):
    response = client.chat.completions.create(
        model='gpt-4o',
        messages=[{'role': 'user', 'content': f'''Change the following passage while preserving its content but using easier, simpler English. If the passage contains more than 5 sentences, summarize it into 5 sentences. Simply return the text:\n\n{value}'''}],
        max_tokens=3072
    )
    return response.choices[0].message.content
    
# Function to elevate English text
def en_elevate(value):
    response = client.chat.completions.create(
        model='gpt-4o',
        messages=[{'role': 'user', 'content': f'''Change the following passage while preserving its content but using more advanced, more sophisticated English. If the passage contains fewer than 3 sentences, expand it to 3 sentences. If it has exactly 3 sentences, expand it to 4 sentences, and if it has 4 sentences, expand it to 5 sentences. Simply return the text:\n\n{value}'''}],
        max_tokens=3072
    )
    return response.choices[0].message.content
    
# Function to describe English text
def en_describe(value):
    response = client.chat.completions.create(
        model='gpt-4o-mini',
        messages=[{'role': 'user', 'content': f'''Transform the given passage into an explanatory text that describes the subject in detail. The text should be between 5 to 10 English sentences in plain text, organized into 2 to 3 paragraphs without any special formatting:\n\n{value}'''}],
        max_tokens=3072
    )
    return response.choices[0].message.content
    
# Function to argue in English text
def en_argue(value):
    response = client.chat.completions.create(
        model='gpt-4o-mini',
        messages=[{'role': 'user', 'content': f'''Change the given passage into a persuasive essay that presents a specific argument or viewpoint. The essay should be between 5 to 10 English sentences in plain text, organized into 2 to 3 paragraphs without any special formatting:\n\n{value}'''}],
        max_tokens=3072
    )
    return response.choices[0].message.content
    
# Function to narrate in English text
def en_narrate(value):
    response = client.chat.completions.create(
        model='gpt-4o-mini',
        messages=[{'role': 'user', 'content': f'''Transform the given passage into a story focused on a single human character, highlighting their emotions. The narrative should be between 5 to 10 English sentences in plain text, organized into 2 to 3 paragraphs without any special formatting:\n\n{value}'''}],
        max_tokens=3072
    )
    return response.choices[0].message.content

# Function to recontextualize English text
def en_recontext(value):
    response = client.chat.completions.create(
        model='gpt-4o',
        messages=[{'role': 'user', 'content': f'''Modify the given text by changing its time period, country setting, and social class, while keeping it structurally similar to the original. The text should be between 5 to 10 English sentences in plain text, organized into 2 to 3 paragraphs without any special formatting:\n\n{value}'''}],
        max_tokens=3072
    )
    return response.choices[0].message.content
    
# Function to reimagine English text
def en_reimagine(value):
    response = client.chat.completions.create(
        model='gpt-4o',
        messages=[{'role': 'user', 'content': f'''Develop the given text into a new piece of writing that remains related to the original but evolves creatively while maintaining its original genre. The text should consist of 5 to 10 English sentences organized into 2 to 3 paragraphs, written in plain text without any special formatting:\n\n{value}'''}],
        max_tokens=3072
    )
    return response.choices[0].message.content
    
# Function to reinvent English text
def en_reinvent(value):
    response = client.chat.completions.create(
        model='gpt-4o',
        messages=[{'role': 'user', 'content': f'''Transform the given passage entirely, ensuring that the resulting content is drastically different in every aspect, including the theme. Change the genre, purpose, setting, major plot points, narrative style, and protagonist's personality and role, especially the theme. Regardless of whether the original passage is narrative, expository, or persuasive, convert it into a completely different form, such as a narrative story, an expository essay, a persuasive article, or a formal report. The resulting passage should be between 5 to 10 English sentences in plain text, organized into 2 to 3 paragraphs without any special formatting. The new content should primarily relate to everyday life, society, academics, culture, history, psychology, philosophy, social sciences, natural sciences, or literature:\n\n{value}'''}],
        max_tokens=3072
    )
    return response.choices[0].message.content

# Function to convert text to speech
def en_speak(value, country):
    t = []
    voice = 'en-GB-Wavenet-B' if country == 'gb' else 'en-US-Wavenet-B'
    text_to_mp3(voice, value, 'text')
    audio_path = 'text.mp3'
    with open(audio_path, 'rb') as audio_file:
        audio_content = audio_file.read()
    return base64.b64encode(audio_content).decode('utf-8')
    
# Function to translate text
def en_translate(value, translator):
    if translator == 'google':
        placeholder_double = '<DOUBLE_NEWLINE>'
        placeholder_single = '<SINGLE_NEWLINE>'
        value = value.replace('\n\n', placeholder_double).replace('\n', placeholder_single)
        translated_text = translate_text_with_model('ko', value, model='nmt')
        translated_text = html_std.unescape(translated_text)
        translated_text = translated_text.replace(placeholder_double, '\n\n').replace(placeholder_single, '\n')
        translated_text = '\n'.join(line.lstrip() for line in translated_text.split('\n'))
        return html.Div(translated_text)
    elif translator == 'gpt':
        messages = [
            {'role': 'system', 'content': '''You are an expert in English-Korean translation. Translate the entire text to Korean, ensuring that 'artificial general intelligence' is accurately translated as '인공 일반 지능.' Maintain the original line breaks as they are in the source text. Do not add extra line breaks or additional spacing between lines that were not present in the original text. Also, do not remove line breaks or additional spacing that were present in the original text. When two sentences are separated by a single line break and when they are separated by two line breaks, make sure to distinguish between the two cases. Be careful not to separate paragraphs with two line breaks when the original text uses only a single line break. Simply return the translated text without any explanatory comments or alterations beyond the translation.'''},
            {'role': 'user', 'content': value}
        ]
        response = client.chat.completions.create(
            model='gpt-4o',
            messages=messages,
            max_tokens=3072,
            temperature=0
        )
        return response.choices[0].message.content

# Function to create study material using GPT
def en_study_gpt(value):
    messages = [
        {'role': 'system', 'content': '''You are a competent high school English teacher in Korea. Additionally, you are currently kindly teaching English study content that high school students need to know to adults with high school-level English proficiency.'''},
        {'role': 'user', 'content': f'''You have been given this passage:
KNS Education ardently pursues knowledge and success through genuine education. This institution strives to establish a solid educational foundation, enabling individuals from elementary students to university aspirants to exert their utmost efforts towards their goals. As KNS Education, we have achieved our standing as a premier English education institution through the dedication of exceptional instructors, diligent students, and the support of engaged parents. Rather than resting on our past achievements, we embrace open communication and continue to foster growth.

And you have previously created educational materials based on it:


[Key Vocabulary and Its Meanings]

genuine (adj) 제뉴인 | 진정한 | 여기서는 '진실된'이라는 뜻으로, 진실된 교육 방법을 나타냅니다.
foundation (n) 파운데이션 | 기반 | 교육의 튼튼한 기반을 의미합니다, 즉, 견고한 교육을 통해 미래를 준비하는 것입니다.
aspirants (n) 애스파이런츠 | 지망생 | 대학이나 더 높은 교육을 향해 노력하는 학생들을 지칭합니다.
foster (v) 포스터 | 촉진하다 | 성장을 장려하고 뒷받침하는 행위를 말하며, 계속해서 발전하기 위한 노력을 강조합니다.
adapt (v) 어댑트 | 적응하다 :| 변화하는 상황에 맞추어 자신이나 상황을 조절하는 것을 말하며, 특히 교육 방법의 진화를 의미합니다.
pursue (v) 퍼슈 | 추구하다 | 지식과 성공을 적극적으로 추구하는 것을 의미합니다.
enable (v) 이네이블 | 가능하게 하다 : 특정한 행동이나 활동을 가능하게 하는 것을 말합니다.
exert (v) 엑저트 | 노력하다 | 특정 목표를 향해 최대한 노력하는 것을 의미합니다.
achieve (v) 어치브 | 달성하다 | 목표나 결과를 성공적으로 이루는 것을 말합니다.
embrace (v) 엠브레이스 | 받아들이다 | 새로운 아이디어나 변화를 기꺼이 받아들이는 태도를 의미합니다.

[IB Reflection and Discussion]

(This is material for IB classes. IB emphasizes critical thinking, self-reflection, and a global perspective.)

Q: KNS Education passionately pursues knowledge and success, aiming to establish a solid foundation through education. What are your thoughts on this educational philosophy? Could you evaluate how this philosophy has been implemented based on your experience and share your insights?
KNS Education은 지식과 성공을 열정적으로 추구하며, 교육을 통해 견고한 기반을 마련하고자 합니다. 당신은 이러한 교육 철학에 대해 어떻게 생각하시나요? 당신의 경험으로부터 이러한 철학이 어떻게 구현되었는지 판단하고 공유해 주실 수 있나요?

A: Ardent pursuit of knowledge and success through education can significantly impact students' motivation and achievements. By focusing on establishing a solid educational foundation, KNS Education ensures that students are well-prepared to face future challenges. This approach not only supports academic excellence but also encourages personal growth and development.
지식과 성공을 향한 열정적인 추구는 교육을 통해 학생들의 동기 부여와 성취에 크게 영향을 미칠 수 있습니다. 탄탄한 교육적 기초를 확립하는 데 중점을 둠으로써, KNS Education은 학생들이 미래의 도전에 잘 대비할 수 있도록 보장합니다. 이 접근 방식은 학업 우수성을 지원할 뿐만 아니라 개인의 성장과 발전을 장려합니다.


Using the provided passage, create educational materials in plain text format, without numbering or emphasizing, following the same layout. Note that you must clearly distinguish between the parts written in English and those written in Korean:

{value}'''}
    ]
    response = client.chat.completions.create(
        model='gpt-4o',
        messages=messages,
        max_tokens=3072,
        temperature=0.3
    )
    return response.choices[0].message.content

def us_tutor(value):
    messages = [
        {'role': 'system', 'content': '''
You are an American and a writing tutor. You are given a text that can be in any language. Your task is to provide corrections and feedback to improve the text. Do not translate the original text; only provide corrections and feedback.

Regardless of the text's language, provide all feedback in English.

Please correct every grammatical error, improve sentence structure, and provide constructive feedback on all aspects of the text. Ensure that no errors or areas for improvement are missed.

A sentence like "I go to school to get my stuff" may seem correct because of the idiomatic expression "go to school," but that phrase is only appropriate when referring to attending school to study. If the purpose is to retrieve something, meaning you are going to a specific building for a different reason, you should change it to "go to the school." Therefore, instead of relying solely on habitual checks, you must pay close attention to the context and intent of the text to determine what is correct.

You should also keep in mind the possibility that this might be a famous piece of writing by a great author or a highly poetic expression. In such cases, carelessly making changes can be viewed as ignorant.

Use plain text without any styling.

When correcting "The student study hard. He got good grades." without any line break, you would, for example, change it to "The student studies diligently. So he gets good grades."
When correcting "The student study hard.\nHe got good grades." with exactly one line break, you would change it to "The student studies diligently.\nSo he gets good grades."
When correcting "The student study hard.\n\nHe got good grades." with two line breaks, you would change it to "The student studies diligently.\n\nSo he gets good grades."

For the explanations and feedback, use simple and easy-to-understand English. Ensure that the original text and corrections remain in their original language.'''},
        {'role': 'user', 'content': f'''
You are given the text:
{value}

Please provide correction and feedback for the given text as shown in the example below.


Example Text in English:
The student study hard, so he got good grades. He need to go to school to get his stuff.

Response:

1. Grammar Errors / Suggestions

- The student study hard, → The student studies hard,
The subject "The student" is third-person singular, so the verb should be "studies."

- so he got good grades. → so he gets good grades.
Maintain consistent tense by changing "got" to "gets."

- He need to go to school → He needs to go to the school
The subject "He" is third-person singular, so the verb must be "needs." Since he is not going to study but rather going for another purpose, use "the school." If you say "go to his school," it implies he lost his items at his own school, which might not be guaranteed.

- to get his stuff. → to get his things
"stuff" is somewhat informal. If you want a more formal tone, use "things" or "belongings."

2. Content Evaluation / Structure Improvement

- The student studies hard, so he gets good grades.
This sentence is grammatically correct, but you can emphasize the cause-and-effect relationship by using "Because."
Example: Because the student studies hard, he gets good grades.

3. Style and Expression

- Instead of hard, you can use diligently to make the sentence sound more polished. Instead of stuff, you can use things or belongings for a more formal style.
Example: Because the student studies diligently, he gets good grades. He needs to go to the school to get his things.

4. Final Corrected Sentence

Because the student studies diligently, he gets good grades. He needs to go to the school to get his things.


Example Text in Korean
학생은 공부를 열심히 해요. 그래서 그는 좋은 성적을 받았어요. 그는 물건을 찾을 목적을 위해 학교 가야 해요.

Response:

1. Grammar Errors / Suggestions

- 학생은 공부를 열심히 해요. → 학생은 열심히 공부해요.
Reordering subject and verb makes the sentence sound more natural in Korean.

- 그래서 그는 좋은 성적을 받았어요.
There is no major grammatical problem here. However, depending on context or mood, you can adjust the connecting word.

- 그는 물건을 찾을 목적을 위해 학교 가야 해요. → 그는 물건을 찾기 위해 학교에 가야 해요.
"목적을 위해" can sound redundant. Also, add the particle "에" before "가야 해요," making it "학교에 가야 해요," which is more natural in Korean.

2 .Content Evaluation / Structure Improvement

- "학생은 열심히 공부해요. 그래서 그는 좋은 성적을 받았어요." shows a clear cause-and-effect relationship.

- The third sentence about going to school to find something presents a different context, so you could use a contrasting or transitional connector such as "그런데" or "하지만," or simply separate the sentences without a connector.
Example (using a transition): 학생은 열심히 공부해서 좋은 성적을 받았어요. 그런데 그는 물건을 찾기 위해 학교에 가야 해요.
Example (omitting the connector): 학생은 열심히 공부해서 좋은 성적을 받았어요. 그는 물건을 찾기 위해 학교에 가야 해요.

3. Style and Expression

- Instead of 열심히, using words like 성실하게 or 꾸준히 can give a more refined tone.

- Redundant phrases such as "목적을 위해" should be simplified to maintain clarity.

- You can choose connectives like "그래서," "그런데," or "하지만" depending on context and intent.
Example: 학생은 성실하게 공부해서 좋은 성적을 받았어요. 그런데 그는 물건을 찾기 위해 학교에 가야 해요.

4. Final Corrected Sentence

If you want to show a change in mood:
학생은 성실하게 공부해서 좋은 성적을 받았어요. 그런데 그는 물건을 찾기 위해 학교에 가야 해요.

If you prefer a concise style:
학생은 성실하게 공부해서 좋은 성적을 받았어요. 그는 물건을 찾기 위해 학교에 가야 해요.
'''}
    ]
    response = client.chat.completions.create(
        model='gpt-4o',
        messages=messages,
        max_tokens=4096,
        temperature=0.3
    )
    return response.choices[0].message.content

def korean_tutor(value):
    messages = [
        {'role': 'system', 'content': '''
You are a Korean and a writing tutor. You are given a text that can be in any language. Your task is to provide corrections and feedback to improve the text. Do not translate or change the language of the original text.

Analyze and correct the text based on the grammatical rules, sentence structure, and style appropriate for the language of the text. However, all explanations and feedback should be provided in polite Korean language (경어체), while strictly adhering to the language norms of the original text.

Do not suggest changes that involve replacing expressions with those from another language or based on Korean language norms.

Please correct every grammatical error, improve sentence structure, and provide constructive feedback on all aspects of the text. Ensure that no errors or areas for improvement are missed.

A sentence like "I go to school to get my stuff" may seem correct because of the idiomatic expression "go to school," but that phrase is only appropriate when referring to attending school to study. If the purpose is to retrieve something, meaning you are going to a specific building for a different reason, you should change it to "go to the school." Therefore, instead of relying solely on habitual checks, you must pay close attention to the context and intent of the text to determine what is correct.

You should also keep in mind the possibility that this might be a famous piece of writing by a great author or a highly poetic expression. In such cases, carelessly making changes can be viewed as ignorant.

Use plain text without any styling.

When correcting "The student study hard. He got good grades." without any line break, you would, for example, change it to "The student studies diligently. So he gets good grades."
When correcting "The student study hard.\nHe got good grades." with exactly one line break, you would change it to "The student studies diligently.\nSo he gets good grades."
When correcting "The student study hard.\n\nHe got good grades." with two line breaks, you would change it to "The student studies diligently.\n\nSo he gets good grades."

For the explanations and feedback, use simple and easy-to-understand Korean. Ensure that the original text and corrections remain in their original language.'''},
        {'role': 'user', 'content': f'''
You are given the text:
{value}

Please provide correction and feedback for the given text as shown in the example below.


Example Text in English:

The student study hard, so he got good grades. He need to go to school to get his stuff.

Response:

1. 문법 오류 수정 / 제안

- The student study hard, → The student studies hard,
주어 "The student"는 3인칭 단수 형태의 동사 "studies"가 필요합니다.

- so he got good grades. → so he gets good grades.
일관된 시제를 위해 과거형 "got"을 현재형 "gets"로 변경합니다.

- He need to go to school → He needs to go to the school
주어 "He"도 3인칭 단수이므로 "needs"가 필요합니다. 또한, 공부를 하러 가는 것이 아니라 다른 목적으로 구체적인 학교(건물)에 간다는 의미이기 때문에 정관사 "the"를 붙여 "go to the school"이라고 써야 합니다. "go to his school"을 쓰면 "그가 원래 다니는 학교"라는 전제가 깔리므로, 잃어버린 물건이 반드시 그의 학교에 있다는 확신이 없을 경우에는 이렇게 쓰지 않는 것이 좋습니다.

- to get his stuff. → to get his things
"stuff"는 다소 구어체적인데 문어체에 가까울 필요가 있다면 "things"나 "belongings" 등으로 바꾸는 것도 좋습니다.

2. 내용 평가 및 구조 개선

- The student studies hard, so he gets good grades.
이 문장은 문법적으로 맞지만, 더 명확하고 자연스럽게 개선할 수 있습니다. 원인과 결과가 드러나도록 "Because"를 활용할 수 있습니다.
예시: Because the student studies hard, he gets good grades.

3. 스타일과 표현

- hard 대신 diligently를 사용하면 문장이 더 세련되게 들립니다. 그리고 stuff 대신 things나 belongings는 좀 더 격식 있게 느껴집니다.
예시: Because the student studies diligently, he gets good grades. He needs to go to the school to get his things.

4. 최종 수정된 문장

Because the student studies diligently, he gets good grades. He needs to go to the school to get his things.


Example Text in Korean:

학생은 공부를 열심히 해요. 그래서 그는 좋은 성적을 받았어요. 그는 물건을 찾을 목적을 위해 학교 가야 해요.

Response:

1. 문법 오류 수정 / 제안

- 학생은 공부를 열심히 해요. → 학생은 열심히 공부해요.
주어와 동사의 위치를 바꾸어 문장을 자연스럽게 만듭니다.

- 그래서 그는 좋은 성적을 받았어요.
문법적으로 큰 문제는 없습니다. 맥락과 의도에 따라 접속사를 변경할 수 있습니다.

- 그는 물건을 찾을 목적을 위해 학교 가야 해요. → 그는 물건을 찾기 위해 학교에 가야 해요.
"목적을 위해"는 중복된 표현으로 들릴 수 있으므로, "물건을 찾기 위해"로 간결하게 수정하고, "학교 가야 해요" 앞에 조사 "에"를 넣어 "학교에 가야 해요"로 고쳐주면 자연스럽습니다.

2. 내용 평가 및 구조 개선

- "학생은 열심히 공부해요. 그래서 그는 좋은 성적을 받았어요."는 인과관계를 명확히 드러냅니다.

- 세 번째 문장은 다른 맥락(물건을 찾기 위해 학교에 간다)이므로, 앞 문장과 분위기를 달리하거나 접속사를 달리 써서 자연스러운 흐름을 만들 수 있습니다. 접속사를 생략하고 문장을 분리해도 좋습니다.
예시 (접속사 사용, 부드러운 전환): 학생은 열심히 공부해서 좋은 성적을 받았어요. 그런데 그는 물건을 찾기 위해 학교에 가야 해요.
예시 (접속사 생략, 간결하게): 학생은 열심히 공부해서 좋은 성적을 받았어요. 그는 물건을 찾기 위해 학교에 가야 해요.

3. 스타일과 표현

- "열심히" 대신 "성실하게"나 "꾸준히" 같은 표현을 쓰면 문장이 좀 더 세련되게 들릴 수 있습니다.

- "목적을 위해"처럼 중복 표현이 될 수 있는 부분은 과감히 줄이는 것이 좋습니다.

- 접속사("그래서", "그런데", "하지만" 등)는 문맥과 화자의 의도를 고려해 선택합니다.
예시: 학생은 성실하게 공부해서 좋은 성적을 받았어요. 그런데 그는 물건을 찾기 위해 학교에 가야 해요.

4. 최종 수정된 문장

접속사를 사용해 기분 전환을 드러내는 경우:
학생은 성실하게 공부해서 좋은 성적을 받았어요. 그런데 그는 물건을 찾기 위해 학교에 가야 해요.

접속사를 생략하여 간결하게:
학생은 성실하게 공부해서 좋은 성적을 받았어요. 그는 물건을 찾기 위해 학교에 가야 해요.
'''}
    ]
    response = client.chat.completions.create(
        model='gpt-4o',
        messages=messages,
        max_tokens=4096,
        temperature=0.3
    )
    return response.choices[0].message.content

def get_problem_content(problem_index, txt):
    c = cmp.prompt(problem_index)
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    try:
        result, _ = loop.run_until_complete(
            generate_prob(0, c, txt)
        )
    finally:
        loop.close()
    return result

def extract_text_from_images(contents, filename):
    try:
        image_bytes = base64.b64decode(contents.split(',')[1])  
    except Exception as e:
        return ''
        #f'Error decoding base64 content from file {filename}: {str(e)}''

    try:
        # If using pdf2image, convert_from_bytes is needed
        # from pdf2image import convert_from_bytes
        if filename.lower().endswith('.pdf'):
            # images = convert_from_bytes(image_bytes)  # for example
            # text = ""
            # for img in images:
            #     with io.BytesIO() as output:
            #         img.save(output, format='PNG')
            #         image_bytes_png = output.getvalue()
            #         image = vision.Image(content=image_bytes_png)
            #         response = vision_client.document_text_detection(image=image)
            #         if response.error.message:
            #             raise Exception(response.error.message)
            #         if hasattr(response, 'full_text_annotation') and response.full_text_annotation:
            #             text += response.full_text_annotation.text
            # if not text:
            #     raise Exception('No text detected in the uploaded PDF file.')
            # return text

            # For now, placeholder if user does not have pdf2image installed:
            return ''
        else:
            image = vision.Image(content=image_bytes)
            response = vision_client.text_detection(image=image)
            if response.error.message:
                raise Exception('') #(response.error.message)
            text = response.full_text_annotation.text
            if not text:
                raise Exception('')
            return text

    except Exception as e:
        return ''
    return ''
