Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -100,11 +100,10 @@ def translate_to_english(text):
|
|
| 100 |
return translated_text
|
| 101 |
except Exception as e:
|
| 102 |
logger.error(f"خطا در ترجمه: {str(e)}")
|
| 103 |
-
return text
|
| 104 |
|
| 105 |
def check_plagiarism(text):
|
| 106 |
try:
|
| 107 |
-
# ترجمه به انگلیسی
|
| 108 |
translated_text = translate_to_english(text)
|
| 109 |
query = translated_text[:100]
|
| 110 |
|
|
@@ -112,14 +111,22 @@ def check_plagiarism(text):
|
|
| 112 |
url_scholar = f"https://scholar.google.com/scholar?q={query}"
|
| 113 |
response_scholar = requests.get(url_scholar, headers={"User-Agent": "Mozilla/5.0"})
|
| 114 |
soup_scholar = BeautifulSoup(response_scholar.text, 'html.parser')
|
| 115 |
-
results_scholar = [
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
logger.info(f"نتایج Google Scholar: {results_scholar}")
|
| 117 |
|
| 118 |
# جستجو در arXiv
|
| 119 |
url_arxiv = f"https://arxiv.org/search/?query={query}&searchtype=all&source=header"
|
| 120 |
response_arxiv = requests.get(url_arxiv, headers={"User-Agent": "Mozilla/5.0"})
|
| 121 |
soup_arxiv = BeautifulSoup(response_arxiv.text, 'html.parser')
|
| 122 |
-
results_arxiv = [
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
logger.info(f"نتایج arXiv: {results_arxiv}")
|
| 124 |
|
| 125 |
all_results = results_scholar + results_arxiv
|
|
@@ -128,13 +135,13 @@ def check_plagiarism(text):
|
|
| 128 |
|
| 129 |
max_similarity = 0
|
| 130 |
matched_texts = []
|
| 131 |
-
for
|
| 132 |
-
similarity = SequenceMatcher(None, translated_text[:500],
|
| 133 |
if similarity > max_similarity:
|
| 134 |
max_similarity = similarity
|
| 135 |
-
matched_texts = [
|
| 136 |
elif similarity == max_similarity:
|
| 137 |
-
matched_texts.append(
|
| 138 |
|
| 139 |
time.sleep(1)
|
| 140 |
similarity_percent = max_similarity * 100
|
|
@@ -151,12 +158,13 @@ def suggest_resources(text):
|
|
| 151 |
url_scholar = f"https://scholar.google.com/scholar?q={query}"
|
| 152 |
response_scholar = requests.get(url_scholar, headers={"User-Agent": "Mozilla/5.0"})
|
| 153 |
soup_scholar = BeautifulSoup(response_scholar.text, 'html.parser')
|
| 154 |
-
papers_scholar = [h.get_text().strip() for h in soup_scholar.find_all('h3')[:3]]
|
| 155 |
|
| 156 |
url_arxiv = f"https://arxiv.org/search/?query={query}&searchtype=all&source=header"
|
| 157 |
response_arxiv = requests.get(url_arxiv, headers={"User-Agent": "Mozilla/5.0"})
|
| 158 |
soup_arxiv = BeautifulSoup(response_arxiv.text, 'html.parser')
|
| 159 |
-
papers_arxiv = [paper.get_text().strip()
|
|
|
|
| 160 |
|
| 161 |
resources = papers_scholar + papers_arxiv if papers_scholar else papers_arxiv
|
| 162 |
time.sleep(1)
|
|
@@ -170,52 +178,65 @@ def evaluate_quality(docs, sections):
|
|
| 170 |
score = 0
|
| 171 |
explanation = []
|
| 172 |
suggestions = []
|
|
|
|
| 173 |
|
| 174 |
# معیار 1: منابع
|
| 175 |
ref_count = len(re.findall(r"\[\d+\]|[A-Za-z]+\s+\d{4}", text))
|
| 176 |
if ref_count > 10:
|
| 177 |
-
score +=
|
| 178 |
explanation.append("منابع کافی و قابل استناد (بیش از 10 ارجاع).")
|
| 179 |
elif ref_count > 0:
|
| 180 |
-
score +=
|
| 181 |
explanation.append("منابع موجود اما محدود (کمتر از 10 ارجاع).")
|
| 182 |
-
suggestions.append("حداقل 5 منبع معتبر
|
| 183 |
else:
|
| 184 |
explanation.append("منابع کافی یافت نشد.")
|
| 185 |
-
suggestions.append("بخش منابع را با حداقل 10 ارجاع
|
|
|
|
| 186 |
|
| 187 |
-
# معیار 2: انسجام
|
| 188 |
words = text.split()
|
| 189 |
word_freq = Counter(words).most_common(10)
|
|
|
|
| 190 |
if word_freq and word_freq[0][1] > len(words) * 0.02:
|
| 191 |
score += 25
|
| 192 |
explanation.append("انسجام متنی خوب (تمرکز بر موضوع اصلی).")
|
| 193 |
else:
|
| 194 |
explanation.append("انسجام متنی ضعیف (پراکندگی موضوعی).")
|
| 195 |
-
suggestions.append(f"
|
|
|
|
| 196 |
|
| 197 |
-
# معیار 3: جداول/شکلها
|
| 198 |
if re.search(r"جدول|شکل|Table|Figure", text, re.I):
|
| 199 |
score += 20
|
| 200 |
explanation.append("استفاده از جداول یا شکلها برای پشتیبانی یافتهها.")
|
| 201 |
else:
|
| 202 |
explanation.append("عدم استفاده از جداول یا شکلها.")
|
| 203 |
-
suggestions.append("حداقل یک جدول
|
| 204 |
|
| 205 |
-
# معیار 4: عمق تحلیل
|
| 206 |
analysis_text = " ".join([doc.page_content for doc in sections.get("نتایج", []) + sections.get("بحث", [])])
|
| 207 |
if len(analysis_text.split()) > 1000:
|
| 208 |
-
score +=
|
| 209 |
explanation.append("عمق تحلیل قابل قبول (بخش نتایج/بحث طولانی).")
|
| 210 |
else:
|
| 211 |
explanation.append("عمق تحلیل محدود (بخش نتایج/بحث کوتاه).")
|
| 212 |
-
suggestions.append("بخش نتایج و بحث را با
|
| 213 |
|
| 214 |
-
#
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
score = max(min(score, 100), 10)
|
| 221 |
return score, "; ".join(explanation), "; ".join(suggestions), auto_fix
|
|
@@ -312,33 +333,33 @@ def academic_chatbot(pdf_file, mode, query, language, detail_level, section_drop
|
|
| 312 |
if error:
|
| 313 |
return error
|
| 314 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 315 |
vector_store = None
|
| 316 |
if mode in ["تحلیل آکادمیک (RAG)", "چک سرقت ادبی", "ارزیابی کیفیت"]:
|
| 317 |
-
target_docs = docs if section_dropdown == "کل سند" else sections.get(section_dropdown, docs)
|
| 318 |
vector_store, vectordb_error = create_vector_db(target_docs)
|
| 319 |
if vectordb_error:
|
| 320 |
return vectordb_error
|
| 321 |
|
| 322 |
-
chain = create_conversation_chain(vector_store,
|
| 323 |
try:
|
| 324 |
if mode == "خلاصه خودکار":
|
| 325 |
-
context = " ".join([doc.page_content for doc in docs])
|
| 326 |
time.sleep(2)
|
| 327 |
result = chain.invoke({"context": context[:5000]})["text"]
|
| 328 |
elif mode == "چک سرقت ادبی":
|
| 329 |
-
context = " ".join([doc.page_content for doc in docs if section_dropdown == "کل سند" or doc in sections.get(section_dropdown, [])])
|
| 330 |
plagiarism_result = check_plagiarism(context)
|
| 331 |
result = plagiarism_result
|
| 332 |
elif mode == "ارزیابی کیفیت":
|
| 333 |
-
|
| 334 |
-
score, explanation, suggestions, auto_fix = evaluate_quality(docs, sections)
|
| 335 |
time.sleep(2)
|
| 336 |
result = chain.invoke({"context": context[:5000], "score": score, "explanation": explanation, "suggestions": suggestions})["text"] + auto_fix
|
| 337 |
else:
|
| 338 |
result = chain.invoke({"question": query, "chat_history": []})["answer"]
|
| 339 |
|
| 340 |
if mode not in ["چک سرقت ادبی", "ارزیابی کیفیت"]:
|
| 341 |
-
resources = suggest_resources(
|
| 342 |
result += "\n\n**منابع پیشنهادی:**\n" + "\n".join(resources)
|
| 343 |
|
| 344 |
return f"{result}\n\n⏱ زمان پردازش: {time.time() - start_time:.2f} ثانیه"
|
|
|
|
| 100 |
return translated_text
|
| 101 |
except Exception as e:
|
| 102 |
logger.error(f"خطا در ترجمه: {str(e)}")
|
| 103 |
+
return text
|
| 104 |
|
| 105 |
def check_plagiarism(text):
|
| 106 |
try:
|
|
|
|
| 107 |
translated_text = translate_to_english(text)
|
| 108 |
query = translated_text[:100]
|
| 109 |
|
|
|
|
| 111 |
url_scholar = f"https://scholar.google.com/scholar?q={query}"
|
| 112 |
response_scholar = requests.get(url_scholar, headers={"User-Agent": "Mozilla/5.0"})
|
| 113 |
soup_scholar = BeautifulSoup(response_scholar.text, 'html.parser')
|
| 114 |
+
results_scholar = []
|
| 115 |
+
for item in soup_scholar.find_all('h3', class_='gs_rt')[:5]:
|
| 116 |
+
title = item.get_text()
|
| 117 |
+
link = item.find('a')['href'] if item.find('a') else "لینک موجود نیست"
|
| 118 |
+
results_scholar.append((title, link))
|
| 119 |
logger.info(f"نتایج Google Scholar: {results_scholar}")
|
| 120 |
|
| 121 |
# جستجو در arXiv
|
| 122 |
url_arxiv = f"https://arxiv.org/search/?query={query}&searchtype=all&source=header"
|
| 123 |
response_arxiv = requests.get(url_arxiv, headers={"User-Agent": "Mozilla/5.0"})
|
| 124 |
soup_arxiv = BeautifulSoup(response_arxiv.text, 'html.parser')
|
| 125 |
+
results_arxiv = []
|
| 126 |
+
for item in soup_arxiv.find_all('p', class_='title')[:5]:
|
| 127 |
+
title = item.get_text().strip()
|
| 128 |
+
link = item.find_previous('a', class_='arxiv-url')['href'] if item.find_previous('a', class_='arxiv-url') else "لینک موجود نیست"
|
| 129 |
+
results_arxiv.append((title, link))
|
| 130 |
logger.info(f"نتایج arXiv: {results_arxiv}")
|
| 131 |
|
| 132 |
all_results = results_scholar + results_arxiv
|
|
|
|
| 135 |
|
| 136 |
max_similarity = 0
|
| 137 |
matched_texts = []
|
| 138 |
+
for title, link in all_results:
|
| 139 |
+
similarity = SequenceMatcher(None, translated_text[:500], title).ratio()
|
| 140 |
if similarity > max_similarity:
|
| 141 |
max_similarity = similarity
|
| 142 |
+
matched_texts = [f"{title} (لینک: {link})"]
|
| 143 |
elif similarity == max_similarity:
|
| 144 |
+
matched_texts.append(f"{title} (لینک: {link})")
|
| 145 |
|
| 146 |
time.sleep(1)
|
| 147 |
similarity_percent = max_similarity * 100
|
|
|
|
| 158 |
url_scholar = f"https://scholar.google.com/scholar?q={query}"
|
| 159 |
response_scholar = requests.get(url_scholar, headers={"User-Agent": "Mozilla/5.0"})
|
| 160 |
soup_scholar = BeautifulSoup(response_scholar.text, 'html.parser')
|
| 161 |
+
papers_scholar = [f"{h.get_text().strip()} (لینک: {h.find('a')['href']})" for h in soup_scholar.find_all('h3')[:3] if h.find('a')]
|
| 162 |
|
| 163 |
url_arxiv = f"https://arxiv.org/search/?query={query}&searchtype=all&source=header"
|
| 164 |
response_arxiv = requests.get(url_arxiv, headers={"User-Agent": "Mozilla/5.0"})
|
| 165 |
soup_arxiv = BeautifulSoup(response_arxiv.text, 'html.parser')
|
| 166 |
+
papers_arxiv = [f"{paper.get_text().strip()} (لینک: {paper.find_previous('a', class_='arxiv-url')['href']})"
|
| 167 |
+
for paper in soup_arxiv.find_all('p', class_='title')[:2] if paper.find_previous('a', class_='arxiv-url')]
|
| 168 |
|
| 169 |
resources = papers_scholar + papers_arxiv if papers_scholar else papers_arxiv
|
| 170 |
time.sleep(1)
|
|
|
|
| 178 |
score = 0
|
| 179 |
explanation = []
|
| 180 |
suggestions = []
|
| 181 |
+
auto_fix = ""
|
| 182 |
|
| 183 |
# معیار 1: منابع
|
| 184 |
ref_count = len(re.findall(r"\[\d+\]|[A-Za-z]+\s+\d{4}", text))
|
| 185 |
if ref_count > 10:
|
| 186 |
+
score += 30
|
| 187 |
explanation.append("منابع کافی و قابل استناد (بیش از 10 ارجاع).")
|
| 188 |
elif ref_count > 0:
|
| 189 |
+
score += 15
|
| 190 |
explanation.append("منابع موجود اما محدود (کمتر از 10 ارجاع).")
|
| 191 |
+
suggestions.append("حداقل 5 منبع معتبر از مجلات علمی معتبر (مانند IEEE یا Springer) اضافه کنید.")
|
| 192 |
else:
|
| 193 |
explanation.append("منابع کافی یافت نشد.")
|
| 194 |
+
suggestions.append("بخش منابع را با حداقل 10 ارجاع از مقالات Peer-Reviewed تکمیل کنید.")
|
| 195 |
+
auto_fix += "\n**اصلاح خودکار - نمونه ارجاعات:**\n[1] Smith, J. (2020). 'Sample Study', Journal of Science."
|
| 196 |
|
| 197 |
+
# معیار 2: انسجام و بار علمی
|
| 198 |
words = text.split()
|
| 199 |
word_freq = Counter(words).most_common(10)
|
| 200 |
+
keywords = [word[0] for word in word_freq[:3]] if word_freq else ["تحقیق", "نتایج", "روش"]
|
| 201 |
if word_freq and word_freq[0][1] > len(words) * 0.02:
|
| 202 |
score += 25
|
| 203 |
explanation.append("انسجام متنی خوب (تمرکز بر موضوع اصلی).")
|
| 204 |
else:
|
| 205 |
explanation.append("انسجام متنی ضعیف (پراکندگی موضوعی).")
|
| 206 |
+
suggestions.append(f"تمرکز متن را با استفاده بیشتر از کلمات کلیدی مثل {', '.join(keywords)} تقویت کنید.")
|
| 207 |
+
auto_fix += f"\n**اصلاح خودکار - جمله پیشنهادی:**\nاین تحقیق بر {keywords[0]} و {keywords[1]} متمرکزه و نتایج مهمی ارائه میده."
|
| 208 |
|
| 209 |
+
# معیار 3: استفاده از جداول/شکلها
|
| 210 |
if re.search(r"جدول|شکل|Table|Figure", text, re.I):
|
| 211 |
score += 20
|
| 212 |
explanation.append("استفاده از جداول یا شکلها برای پشتیبانی یافتهها.")
|
| 213 |
else:
|
| 214 |
explanation.append("عدم استفاده از جداول یا شکلها.")
|
| 215 |
+
suggestions.append("برای پشتیبانی از یافتهها، حداقل یک جدول برای دادهها و یک شکل برای روندها اضافه کنید.")
|
| 216 |
|
| 217 |
+
# معیار 4: عمق تحلیل و بار علمی
|
| 218 |
analysis_text = " ".join([doc.page_content for doc in sections.get("نتایج", []) + sections.get("بحث", [])])
|
| 219 |
if len(analysis_text.split()) > 1000:
|
| 220 |
+
score += 25
|
| 221 |
explanation.append("عمق تحلیل قابل قبول (بخش نتایج/بحث طولانی).")
|
| 222 |
else:
|
| 223 |
explanation.append("عمق تحلیل محدود (بخش نتایج/بحث کوتاه).")
|
| 224 |
+
suggestions.append("بخش نتایج و بحث را با تحلیل دقیقتر (مثل مقایسه با مقالات مشابه) گسترش دهید.")
|
| 225 |
|
| 226 |
+
# سنجش بار علمی با منابع جهانی
|
| 227 |
+
try:
|
| 228 |
+
translated_text = translate_to_english(text[:1000])
|
| 229 |
+
query = " ".join(translated_text.split()[:5])
|
| 230 |
+
url_arxiv = f"https://arxiv.org/search/?query={query}&searchtype=all&source=header"
|
| 231 |
+
response_arxiv = requests.get(url_arxiv, headers={"User-Agent": "Mozilla/5.0"})
|
| 232 |
+
soup_arxiv = BeautifulSoup(response_arxiv.text, 'html.parser')
|
| 233 |
+
arxiv_titles = [paper.get_text().strip() for paper in soup_arxiv.find_all('p', class_='title')[:3]]
|
| 234 |
+
if arxiv_titles:
|
| 235 |
+
suggestions.append(f"برای افزایش بار علمی، به موضوعات مشابه در مقالات arXiv مثل '{arxiv_titles[0]}' رجوع کنید.")
|
| 236 |
+
time.sleep(1)
|
| 237 |
+
except Exception as e:
|
| 238 |
+
logger.error(f"خطا در سنجش بار علمی: {str(e)}")
|
| 239 |
+
suggestions.append("مقایسه با منابع علمی جهانی به دلیل خطا انجام نشد.")
|
| 240 |
|
| 241 |
score = max(min(score, 100), 10)
|
| 242 |
return score, "; ".join(explanation), "; ".join(suggestions), auto_fix
|
|
|
|
| 333 |
if error:
|
| 334 |
return error
|
| 335 |
|
| 336 |
+
# انتخاب بخش موردنظر
|
| 337 |
+
target_docs = docs if section_dropdown == "کل سند" else sections.get(section_dropdown, docs)
|
| 338 |
+
context = " ".join([doc.page_content for doc in target_docs])
|
| 339 |
+
|
| 340 |
vector_store = None
|
| 341 |
if mode in ["تحلیل آکادمیک (RAG)", "چک سرقت ادبی", "ارزیابی کیفیت"]:
|
|
|
|
| 342 |
vector_store, vectordb_error = create_vector_db(target_docs)
|
| 343 |
if vectordb_error:
|
| 344 |
return vectordb_error
|
| 345 |
|
| 346 |
+
chain = create_conversation_chain(vector_store, target_docs, mode, language, detail_level, section_dropdown)
|
| 347 |
try:
|
| 348 |
if mode == "خلاصه خودکار":
|
|
|
|
| 349 |
time.sleep(2)
|
| 350 |
result = chain.invoke({"context": context[:5000]})["text"]
|
| 351 |
elif mode == "چک سرقت ادبی":
|
|
|
|
| 352 |
plagiarism_result = check_plagiarism(context)
|
| 353 |
result = plagiarism_result
|
| 354 |
elif mode == "ارزیابی کیفیت":
|
| 355 |
+
score, explanation, suggestions, auto_fix = evaluate_quality(target_docs, sections)
|
|
|
|
| 356 |
time.sleep(2)
|
| 357 |
result = chain.invoke({"context": context[:5000], "score": score, "explanation": explanation, "suggestions": suggestions})["text"] + auto_fix
|
| 358 |
else:
|
| 359 |
result = chain.invoke({"question": query, "chat_history": []})["answer"]
|
| 360 |
|
| 361 |
if mode not in ["چک سرقت ادبی", "ارزیابی کیفیت"]:
|
| 362 |
+
resources = suggest_resources(context)
|
| 363 |
result += "\n\n**منابع پیشنهادی:**\n" + "\n".join(resources)
|
| 364 |
|
| 365 |
return f"{result}\n\n⏱ زمان پردازش: {time.time() - start_time:.2f} ثانیه"
|