newtestingdanish / test_essay_analysis.py
aghaai's picture
Fresh commit of all updated files
459923e
#!/usr/bin/env python3
"""
Test script for the essay analysis endpoint to verify fixes for large texts and special characters.
"""
import requests
import json
import time
def test_essay_analysis():
"""Test the essay analysis endpoint with the problematic text."""
# The problematic essay text from the user
essay_text = '''Essay: "Corruption is a malaise that afflicts the whole nation." — Nelson Mandela Corruption, often dubbed as the "mother of all evils," is a destructive force that erodes the social, economic, and political fabric of a country. In Pakistan, corruption has taken root at every level of society, ranging from petty bribery to grand-scale embezzlement. Nothing hampers a nation's development more than systemic corruption, and unfortunately, Pakistan is a prime example of how deeply this menace can affect a society. The economic consequences of corruption are staggering. According to the World Bank, Pakistan loses nearly ₨ 8.5 trillion annually due to corrupt practices. Tax evasion alone costs ₨ 2 trillion (FBR). Additionally, the International Labour Organization (ILO) reports that 10% of Pakistani youth remain unemployed as a result of corruption stifling job creation and fair recruitment. These financial leakages cripple infrastructure, disrupt development, and entrench poverty. Furthermore, inflation is closely tied to corruption. As black money is funneled abroad, it increases the demand for foreign currencies, particularly the US dollar, leading to the devaluation of the Pakistani rupee. According to Transparency International, from 2008 to 2021, illicit funds were laundered abroad, creating artificial scarcity in local currency and spurring inflation. Street crime and social unrest also thrive in corrupt environments. From 2021 to 2024, street crimes in urban centers like Karachi saw exponential increases (Pakistan Police Data). A society plagued by economic despair and injustice inevitably turns toward criminal activity for survival. State institutions are not spared either. Sectors such as police, judiciary, and taxation top the list of most corrupt departments in Pakistan (Transparency International). Kickbacks and bribes in mega projects—such as the ₨ 100 billion loss in the Nandipur power project (NEPRA)—demonstrate the scale of institutional decay. Business scandals, such as the Pakistan Steel Mills and the 2018 Fake Bank Accounts case, have undermined public trust and foreign investor confidence. Healthcare and education also fall victim. Around 30% of hospitals lack basic medical facilities (MOH), and 22 million children remain out of school (UNICEF). The proliferation of fake medical degrees further endangers public welfare. This inequality results in disenfranchised populations and rising crime rates. The root causes of corruption are many. Foremost is the lack of accountability and transparency. Ranked 140th on the Corruption Perception Index, Pakistan's institutions often operate behind opaque veils. Political instability, intermittent democracy, and the power tussles between civilian and military leaderships also create fertile ground for corrupt elites to flourish. The judiciary, another key pillar, is overwhelmed. With 1.5 million pending cases, justice is both delayed and denied. This overburdened legal system enables corrupt actors to escape unpunished, eroding public faith in the rule of law. Additionally, nepotism and red-tapism ensure that merit is sidelined in favor of connections. Overlapping bureaucratic jurisdictions only add to confusion and inefficiency, creating more opportunities for bribes and manipulation. Despite this grim picture, all hope is not lost. Pakistan can curb corruption with sincere, well-directed efforts. First, state institutions must be empowered through legal reforms. New anti-corruption laws and watchdog mechanisms should be enforced. Simultaneously, tax systems must be digitized to trace evaders effectively and plug leakages. Judicial reforms are equally critical. Fast-tracking corruption cases and ensuring impartial judge appointments would restore faith in the legal system. Media must also be used responsibly to promote civic awareness and highlight corruption cases. Public participation is essential. Citizens must understand their rights and responsibilities in a democracy. Simplified, transparent laws and access to information will discourage malpractice. Civic education and moral training should be emphasized in schools and mosques alike to build a value-driven future generation. In conclusion, corruption lies at the heart of Pakistan's multifaceted crises. It blocks economic growth, aggravates social divisions, and threatens national integrity. It is no longer a question of whether we can afford to fight corruption; rather, it is a question of survival. As long as transparency is treated as a favor rather than a right, Pakistan will remain trapped in this vicious cycle. Yet, through collaborative efforts and moral revival, Pakistan can defeat this menace and secure a just, prosperous future for generations to come.'''
# API endpoint
url = "http://localhost:5000/api/essay-analysis"
# Prepare the request
data = {
"essay_text": essay_text
}
print("Testing essay analysis endpoint...")
print(f"Essay text length: {len(essay_text)} characters")
print(f"Essay word count: {len(essay_text.split())} words")
try:
# Make the request
start_time = time.time()
response = requests.post(url, data=data, timeout=300) # 5 minute timeout
end_time = time.time()
print(f"Request completed in {end_time - start_time:.2f} seconds")
print(f"Response status code: {response.status_code}")
if response.status_code == 200:
result = response.json()
print("✅ Success! Essay analysis completed successfully.")
print(f"Original essay word count: {result.get('originalEssayWordCount', 0)}")
print(f"Rewritten essay word count: {result.get('reWrittenEssayWordCount', 0)}")
print(f"Overall evaluation score: {result.get('overallEssayEvaluationScore', 0)}%")
# Print evaluation sections
evaluation_sections = result.get('evaluationAndScoring', [])
print(f"\nEvaluation sections: {len(evaluation_sections)}")
for section in evaluation_sections:
print(f"- {section.get('label', 'Unknown')}: {section.get('score', 0)}% ({section.get('issuesCount', 0)} issues)")
# Print essay structure
essay_structure = result.get('essayStructure', [])
print(f"\nEssay structure sections: {len(essay_structure)}")
for section in essay_structure:
features = section.get('features', [])
print(f"- {section.get('label', 'Unknown')}: {len(features)} features")
else:
print(f"❌ Error: {response.status_code}")
print(f"Response: {response.text}")
except requests.exceptions.Timeout:
print("❌ Request timed out after 5 minutes")
except requests.exceptions.ConnectionError:
print("❌ Connection error. Make sure the server is running on localhost:5000")
except Exception as e:
print(f"❌ Unexpected error: {str(e)}")
if __name__ == "__main__":
test_essay_analysis()