Naz786 commited on
Commit
68b1f81
Β·
verified Β·
1 Parent(s): 351e535

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -176
app.py CHANGED
@@ -2,7 +2,7 @@ import streamlit as st
2
  import os
3
  import requests
4
  import hashlib
5
- from typing import List, Dict, Any
6
  from datetime import datetime
7
  import json
8
  import re
@@ -11,7 +11,6 @@ import time
11
  import random
12
  import markdown
13
 
14
- # Import required libraries
15
  from crewai import Agent, Task, Crew, Process
16
  from crewai.tools import BaseTool
17
  from groq import Groq
@@ -35,11 +34,8 @@ class AcademicResearchTool(BaseTool):
35
  description: str = "Conduct comprehensive academic research for thesis/synopsis"
36
 
37
  def _run(self, topic: str, research_areas: str) -> str:
38
- """Conduct thorough academic research"""
39
  try:
40
  time.sleep(1)
41
-
42
- # Create multiple search queries for comprehensive research
43
  search_queries = [
44
  f"{topic} research studies",
45
  f"{topic} academic papers",
@@ -47,9 +43,7 @@ class AcademicResearchTool(BaseTool):
47
  f"{topic} methodology",
48
  f"{topic} literature review"
49
  ]
50
-
51
  all_research = []
52
-
53
  with DDGS() as ddgs:
54
  for query in search_queries:
55
  try:
@@ -62,39 +56,30 @@ class AcademicResearchTool(BaseTool):
62
  'url': result.get('href', ''),
63
  'relevance_score': self._calculate_relevance(result.get('body', ''), topic)
64
  })
65
- time.sleep(0.5) # Rate limiting
66
- except Exception as e:
67
  continue
68
-
69
- # Sort by relevance and remove duplicates
70
  unique_research = self._remove_duplicates(all_research)
71
  unique_research.sort(key=lambda x: x['relevance_score'], reverse=True)
72
-
73
- return json.dumps(unique_research[:15]) # Top 15 most relevant sources
74
  except Exception as e:
75
  return f"Research failed: {str(e)}"
76
 
77
  def _calculate_relevance(self, content: str, topic: str) -> float:
78
- """Calculate relevance score for research content"""
79
  topic_words = set(topic.lower().split())
80
  content_words = set(content.lower().split())
81
-
82
  if not topic_words or not content_words:
83
  return 0.0
84
-
85
  intersection = topic_words.intersection(content_words)
86
  return len(intersection) / len(topic_words)
87
 
88
  def _remove_duplicates(self, research_list: List[Dict]) -> List[Dict]:
89
- """Remove duplicate research entries"""
90
  seen_urls = set()
91
  unique_research = []
92
-
93
  for item in research_list:
94
  if item['url'] not in seen_urls:
95
  seen_urls.add(item['url'])
96
  unique_research.append(item)
97
-
98
  return unique_research
99
 
100
  class CitationGeneratorTool(BaseTool):
@@ -102,19 +87,13 @@ class CitationGeneratorTool(BaseTool):
102
  description: str = "Generate proper academic citations and references"
103
 
104
  def _run(self, research_data: str) -> str:
105
- """Generate academic citations from research data"""
106
  try:
107
  research_items = json.loads(research_data)
108
  citations = []
109
-
110
- for i, item in enumerate(research_items[:10]): # Top 10 sources
111
- # Generate citation in APA format
112
  title = item.get('title', 'Unknown Title')
113
  url = item.get('url', '')
114
-
115
- # Extract domain for author/organization
116
  domain = url.split('/')[2] if len(url.split('/')) > 2 else 'Unknown'
117
-
118
  citation = {
119
  'id': f"source_{i+1}",
120
  'title': title,
@@ -124,7 +103,6 @@ class CitationGeneratorTool(BaseTool):
124
  'in_text': f"({domain}, {datetime.now().year})"
125
  }
126
  citations.append(citation)
127
-
128
  return json.dumps(citations)
129
  except Exception as e:
130
  return f"Citation generation failed: {str(e)}"
@@ -134,46 +112,35 @@ class AcademicWritingTool(BaseTool):
134
  description: str = "Analyze and improve academic writing style"
135
 
136
  def _run(self, text: str, academic_level: str) -> str:
137
- """Analyze academic writing quality and suggest improvements"""
138
  try:
139
- # Calculate academic writing metrics
140
  flesch_score = flesch_reading_ease(text)
141
  fk_grade = flesch_kincaid_grade(text)
142
-
143
- # Analyze sentence structure
144
  sentences = text.split('.')
145
  sentence_lengths = [len(s.split()) for s in sentences if s.strip()]
146
  avg_sentence_length = sum(sentence_lengths) / max(len(sentence_lengths), 1)
147
-
148
- # Check for academic writing patterns
149
  academic_patterns = [
150
  "furthermore", "moreover", "additionally", "consequently",
151
  "therefore", "thus", "hence", "accordingly", "subsequently"
152
  ]
153
-
154
  pattern_usage = sum(1 for pattern in academic_patterns if pattern in text.lower())
155
-
156
- # Academic level guidelines
157
  level_guidelines = {
158
  'undergraduate': {
159
- 'target_flesch': 60-80,
160
- 'target_grade': 12-14,
161
- 'sentence_length': 15-25
162
  },
163
  'masters': {
164
- 'target_flesch': 50-70,
165
- 'target_grade': 14-16,
166
- 'sentence_length': 18-30
167
  },
168
  'phd': {
169
- 'target_flesch': 40-60,
170
- 'target_grade': 16-18,
171
- 'sentence_length': 20-35
172
  }
173
  }
174
-
175
- guidelines = level_guidelines.get(academic_level, level_guidelines['masters'])
176
-
177
  analysis = {
178
  'flesch_score': flesch_score,
179
  'fk_grade': fk_grade,
@@ -182,15 +149,12 @@ class AcademicWritingTool(BaseTool):
182
  'target_guidelines': guidelines,
183
  'suggestions': []
184
  }
185
-
186
- # Generate suggestions
187
  if flesch_score > guidelines['target_flesch'][1]:
188
  analysis['suggestions'].append("Consider more complex sentence structures for academic tone")
189
  if avg_sentence_length < guidelines['sentence_length'][0]:
190
  analysis['suggestions'].append("Use longer, more detailed sentences")
191
  if pattern_usage < 3:
192
  analysis['suggestions'].append("Include more academic transition phrases")
193
-
194
  return json.dumps(analysis)
195
  except Exception as e:
196
  return f"Academic analysis failed: {str(e)}"
@@ -200,9 +164,7 @@ class HumanizationTool(BaseTool):
200
  description: str = "Make academic writing sound more human and less AI-like"
201
 
202
  def _run(self, text: str) -> str:
203
- """Apply humanization techniques to academic writing"""
204
  try:
205
- # Common AI patterns in academic writing
206
  ai_patterns = [
207
  "It is important to note that",
208
  "This demonstrates that",
@@ -213,8 +175,6 @@ class HumanizationTool(BaseTool):
213
  "This implies that",
214
  "It can be concluded that"
215
  ]
216
-
217
- # Human alternatives
218
  human_alternatives = [
219
  "Notably,",
220
  "This shows",
@@ -225,13 +185,9 @@ class HumanizationTool(BaseTool):
225
  "This implies",
226
  "Therefore,"
227
  ]
228
-
229
- # Apply replacements
230
  humanized_text = text
231
  for ai_pattern, human_alt in zip(ai_patterns, human_alternatives):
232
  humanized_text = humanized_text.replace(ai_pattern, human_alt)
233
-
234
- # Add natural variations
235
  variations = [
236
  "Interestingly,",
237
  "Surprisingly,",
@@ -239,34 +195,25 @@ class HumanizationTool(BaseTool):
239
  "Significantly,",
240
  "Importantly,"
241
  ]
242
-
243
- # Insert variations at appropriate places
244
  sentences = humanized_text.split('.')
245
- for i in range(1, len(sentences), 3): # Every 3rd sentence
246
  if i < len(sentences) and sentences[i].strip():
247
  variation = random.choice(variations)
248
  sentences[i] = f" {variation} {sentences[i].lstrip()}"
249
-
250
  humanized_text = '.'.join(sentences)
251
-
252
- # Add personal insights (subtle)
253
  personal_insights = [
254
  "Based on the available evidence,",
255
  "From the research findings,",
256
  "Considering the data,",
257
  "In light of these results,"
258
  ]
259
-
260
- # Insert personal insights
261
  if len(sentences) > 5:
262
  insight = random.choice(personal_insights)
263
  sentences[2] = f" {insight} {sentences[2].lstrip()}"
264
-
265
  return '.'.join(sentences)
266
  except Exception as e:
267
  return f"Humanization failed: {str(e)}"
268
 
269
- # Rate limit handling decorator
270
  def rate_limit_handler(max_retries=3, base_delay=2):
271
  def decorator(func):
272
  def wrapper(*args, **kwargs):
@@ -285,18 +232,15 @@ def rate_limit_handler(max_retries=3, base_delay=2):
285
  return decorator
286
 
287
  # Custom LLM class for CrewAI with built-in API
288
- import os
289
- from langchain.llms.base import LLM
290
- from typing import Optional, List, Mapping, Any
291
  import litellm
 
292
 
293
  class BuiltInLLM(LLM):
294
  model_name: str = "groq/llama-3.3-70b-versatile"
295
-
 
296
  def __init__(self):
297
  super().__init__()
298
- # Built-in API key (you can replace this with your own)
299
- self.api_key = "API_KEY" # Replace with actual key
300
  os.environ["GROQ_API_KEY"] = self.api_key
301
  litellm.set_verbose = False
302
 
@@ -306,13 +250,10 @@ class BuiltInLLM(LLM):
306
 
307
  @rate_limit_handler(max_retries=3, base_delay=2)
308
  def _call(self, prompt: str, stop: Optional[List[str]] = None, **kwargs) -> str:
309
- """Call API with rate limiting"""
310
  try:
311
- # Handle longer prompts for thesis writing
312
  if len(prompt.split()) > 1500:
313
  words = prompt.split()
314
  prompt = ' '.join(words[:1500]) + "..."
315
-
316
  response = litellm.completion(
317
  model=self.model_name,
318
  messages=[
@@ -320,11 +261,10 @@ class BuiltInLLM(LLM):
320
  {"role": "user", "content": prompt}
321
  ],
322
  max_tokens=2500,
323
- temperature=0.6, # Balanced creativity and consistency
324
  top_p=0.9,
325
  api_key=self.api_key
326
  )
327
-
328
  time.sleep(2)
329
  return response.choices[0].message.content
330
  except Exception as e:
@@ -335,11 +275,7 @@ class BuiltInLLM(LLM):
335
  def _identifying_params(self) -> Mapping[str, Any]:
336
  return {"model_name": self.model_name}
337
 
338
- # Specialized agents for thesis writing
339
  def create_thesis_agents(llm):
340
- """Create specialized agents for thesis/synopsis writing"""
341
-
342
- # Research Agent
343
  research_agent = Agent(
344
  role="Academic Research Specialist",
345
  goal="Conduct comprehensive academic research and gather credible sources",
@@ -349,8 +285,6 @@ def create_thesis_agents(llm):
349
  allow_delegation=False,
350
  llm=llm
351
  )
352
-
353
- # Thesis Writer Agent
354
  thesis_writer = Agent(
355
  role="Academic Thesis Writer",
356
  goal="Write sophisticated thesis documents that sound completely human-written",
@@ -360,8 +294,6 @@ def create_thesis_agents(llm):
360
  allow_delegation=False,
361
  llm=llm
362
  )
363
-
364
- # Humanization Agent
365
  humanization_agent = Agent(
366
  role="Academic Writing Humanizer",
367
  goal="Make academic writing sound completely human and undetectable",
@@ -371,22 +303,16 @@ def create_thesis_agents(llm):
371
  allow_delegation=False,
372
  llm=llm
373
  )
374
-
375
  return research_agent, thesis_writer, humanization_agent
376
 
377
  def create_thesis_tasks(topic, document_type, academic_level, research_areas, word_count, agents):
378
- """Create tasks for thesis/synopsis writing"""
379
  research_agent, thesis_writer, humanization_agent = agents
380
-
381
- # Task 1: Comprehensive Research
382
  research_task = Task(
383
  description=f"""
384
  Conduct comprehensive academic research for a {document_type} on "{topic}".
385
-
386
  Research Areas: {research_areas}
387
  Academic Level: {academic_level}
388
  Target Length: {word_count} words
389
-
390
  Requirements:
391
  - Find 10-15 credible academic sources
392
  - Gather recent research and developments
@@ -394,22 +320,17 @@ def create_thesis_tasks(topic, document_type, academic_level, research_areas, wo
394
  - Note different perspectives and debates
395
  - Focus on peer-reviewed and scholarly sources
396
  - Include both theoretical and practical aspects
397
-
398
  Provide a detailed research summary with key findings, methodologies, and source analysis.
399
  """,
400
  agent=research_agent,
401
  expected_output="Comprehensive research summary with credible sources and key insights"
402
  )
403
-
404
- # Task 2: Thesis Writing
405
  thesis_task = Task(
406
  description=f"""
407
  Write a complete {document_type} on "{topic}" that sounds completely human-written.
408
-
409
  Academic Level: {academic_level}
410
  Target Length: {word_count} words
411
  Research Areas: {research_areas}
412
-
413
  Requirements:
414
  - Use the comprehensive research provided
415
  - Write in proper academic style for {academic_level} level
@@ -421,7 +342,6 @@ def create_thesis_tasks(topic, document_type, academic_level, research_areas, wo
421
  - Avoid AI-like patterns and formal robotic language
422
  - Include methodology, findings, and implications
423
  - Make it engaging and intellectually rigorous
424
-
425
  Structure:
426
  1. Introduction and background
427
  2. Literature review
@@ -429,19 +349,15 @@ def create_thesis_tasks(topic, document_type, academic_level, research_areas, wo
429
  4. Analysis and findings
430
  5. Discussion and implications
431
  6. Conclusion and recommendations
432
-
433
  Important: Write as if you're a human academic expert sharing original research and insights.
434
  """,
435
  agent=thesis_writer,
436
  expected_output="Complete academic thesis document with proper structure and citations",
437
  dependencies=[research_task]
438
  )
439
-
440
- # Task 3: Humanization and Polish
441
  humanization_task = Task(
442
  description=f"""
443
  Polish and humanize the thesis document to make it completely undetectable as AI-written.
444
-
445
  Requirements:
446
  - Remove any remaining AI patterns
447
  - Improve natural academic flow
@@ -453,62 +369,43 @@ def create_thesis_tasks(topic, document_type, academic_level, research_areas, wo
453
  - Improve readability without losing sophistication
454
  - Ensure proper citation integration
455
  - Make it sound like expert human academic writing
456
-
457
  Focus on making it indistinguishable from high-quality human academic writing.
458
  """,
459
  agent=humanization_agent,
460
  expected_output="Final polished human-sounding academic thesis document",
461
  dependencies=[thesis_task]
462
  )
463
-
464
  return [research_task, thesis_task, humanization_task]
465
 
466
  def run_thesis_writer(topic, document_type, academic_level, research_areas, word_count):
467
- """Run the thesis writing process"""
468
  try:
469
- # Initialize LLM
470
  llm = BuiltInLLM()
471
-
472
- # Create agents
473
  agents = create_thesis_agents(llm)
474
-
475
- # Create tasks
476
  tasks = create_thesis_tasks(topic, document_type, academic_level, research_areas, word_count, agents)
477
-
478
- # Create crew
479
  crew = Crew(
480
  agents=list(agents),
481
  tasks=tasks,
482
  process=Process.sequential,
483
  verbose=True
484
  )
485
-
486
- # Execute with progress tracking
487
  with st.spinner("Creating comprehensive thesis document with AI agents..."):
488
  result = crew.kickoff()
489
-
490
  return result
491
  except Exception as e:
492
  st.error(f"Error in thesis writing: {str(e)}")
493
  return None
494
 
495
- # Streamlit UI
496
  def main():
497
  st.set_page_config(
498
  page_title="Thesis Writer Bot - Academic Document Creator",
499
  page_icon="πŸŽ“",
500
  layout="wide"
501
  )
502
-
503
  st.title("πŸŽ“ Thesis Writer Bot")
504
  st.markdown("*Create sophisticated, human-like thesis and synopsis documents that pass any AI detection*")
505
-
506
- # Sidebar configuration
507
  with st.sidebar:
508
  st.header("ℹ️ About")
509
-
510
  st.success("βœ… Ready to generate your thesis!")
511
-
512
  st.markdown("---")
513
  st.markdown("### 🎯 What This Tool Does")
514
  st.markdown("- Creates original, human-like thesis documents")
@@ -516,7 +413,6 @@ def main():
516
  st.markdown("- Generates proper citations and references")
517
  st.markdown("- Ensures content passes AI detection")
518
  st.markdown("- No plagiarism - completely original content")
519
-
520
  st.markdown("---")
521
  st.markdown("### πŸ“š Document Types")
522
  st.markdown("- **Thesis**: Complete research thesis")
@@ -524,13 +420,11 @@ def main():
524
  st.markdown("- **Dissertation**: PhD-level document")
525
  st.markdown("- **Research Paper**: Academic paper")
526
  st.markdown("- **Literature Review**: Comprehensive review")
527
-
528
  st.markdown("---")
529
  st.markdown("### πŸŽ“ Academic Levels")
530
  st.markdown("- **Undergraduate**: Bachelor's level")
531
  st.markdown("- **Masters**: Graduate level")
532
  st.markdown("- **PhD**: Doctoral level")
533
-
534
  st.markdown("---")
535
  st.markdown("### πŸ”₯ Features")
536
  st.markdown("- **No Plagiarism**: Original research")
@@ -539,38 +433,25 @@ def main():
539
  st.markdown("- **Proper Citations**: Academic references")
540
  st.markdown("- **Research-based**: Credible sources")
541
  st.markdown("- **No Word Limits**: Any length needed")
542
-
543
- # Main content area
544
  col1, col2 = st.columns([1, 1])
545
-
546
  with col1:
547
  st.header("πŸ“ Thesis Request")
548
-
549
- # Topic input
550
  topic = st.text_input(
551
  "What is your thesis/synopsis topic?",
552
  placeholder="e.g., Impact of artificial intelligence on healthcare delivery systems"
553
  )
554
-
555
- # Document type selection
556
  document_types = [
557
  "Thesis", "Synopsis", "Dissertation", "Research Paper",
558
  "Literature Review", "Research Proposal", "Academic Report"
559
  ]
560
  document_type = st.selectbox("Document Type", document_types)
561
-
562
- # Academic level
563
  academic_levels = ["Undergraduate", "Masters", "PhD"]
564
  academic_level = st.selectbox("Academic Level", academic_levels)
565
-
566
- # Research areas
567
  research_areas = st.text_area(
568
  "Specific Research Areas/Focus (Optional)",
569
  placeholder="e.g., methodology, recent developments, case studies, theoretical frameworks...",
570
  height=80
571
  )
572
-
573
- # Word count (no limit)
574
  word_count = st.number_input(
575
  "Target Word Count",
576
  min_value=1000,
@@ -579,25 +460,17 @@ def main():
579
  step=500,
580
  help="No strict limit - write as much as needed"
581
  )
582
-
583
- # Additional requirements
584
  additional_requirements = st.text_area(
585
  "Additional Requirements (Optional)",
586
  placeholder="Specific methodology, theoretical framework, case studies, etc...",
587
  height=100
588
  )
589
-
590
- # Generate button
591
  if st.button("πŸš€ Generate Thesis Document", type="primary", use_container_width=True):
592
  if not topic.strip():
593
  st.error("Please enter a thesis topic!")
594
  else:
595
- # Prepare research areas
596
  research_areas_text = research_areas if research_areas.strip() else "general academic research"
597
-
598
- # Run thesis generation
599
  result = run_thesis_writer(topic, document_type, academic_level, research_areas_text, word_count)
600
-
601
  if result:
602
  st.session_state.generated_thesis = result
603
  st.session_state.thesis_info = {
@@ -609,15 +482,11 @@ def main():
609
  'requirements': additional_requirements
610
  }
611
  st.success("βœ… Thesis document generated successfully!")
612
-
613
  with col2:
614
  st.header("πŸ“„ Generated Thesis")
615
-
616
  if "generated_thesis" in st.session_state:
617
  thesis = st.session_state.generated_thesis
618
  info = st.session_state.thesis_info
619
-
620
- # Display thesis info
621
  st.subheader("πŸ“Š Document Information")
622
  col_info1, col_info2 = st.columns(2)
623
  with col_info1:
@@ -628,21 +497,14 @@ def main():
628
  st.metric("Generated Words", len(str(thesis).split()))
629
  st.metric("Research Areas", info['research_areas'][:20] + "..." if len(info['research_areas']) > 20 else info['research_areas'])
630
  st.metric("Quality", "βœ… Human-like")
631
-
632
- # Display the thesis
633
  st.subheader("πŸ“ Your Thesis Document")
634
-
635
- # Format the thesis nicely
636
  formatted_thesis = str(thesis)
637
-
638
  st.text_area(
639
  "Generated Thesis:",
640
  value=formatted_thesis,
641
  height=400,
642
  help="This is your human-like thesis document"
643
  )
644
-
645
- # Download options
646
  col_dl1, col_dl2 = st.columns(2)
647
  with col_dl1:
648
  st.download_button(
@@ -651,23 +513,16 @@ def main():
651
  file_name=f"{info['topic'].replace(' ', '_')}_{info['type']}.txt",
652
  mime="text/plain"
653
  )
654
-
655
  with col_dl2:
656
- # Create markdown version with academic formatting
657
  markdown_content = f"""# {info['topic']}
658
-
659
  **Document Type:** {info['type']}
660
  **Academic Level:** {info['level']}
661
  **Research Areas:** {info['research_areas']}
662
  **Word Count:** {len(str(thesis).split())}
663
  **Generated:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
664
-
665
  ---
666
-
667
  {formatted_thesis}
668
-
669
  ---
670
-
671
  *This document was generated using advanced AI technology and is designed to be indistinguishable from human academic writing.*
672
  """
673
  st.download_button(
@@ -676,15 +531,10 @@ def main():
676
  file_name=f"{info['topic'].replace(' ', '_')}_{info['type']}.md",
677
  mime="text/markdown"
678
  )
679
-
680
- # Document analysis
681
  st.subheader("πŸ” Document Analysis")
682
-
683
- # Quick stats
684
  actual_words = len(str(thesis).split())
685
  actual_sentences = len(str(thesis).split('.'))
686
  paragraphs = len(str(thesis).split('\n\n'))
687
-
688
  col_stats1, col_stats2, col_stats3 = st.columns(3)
689
  with col_stats1:
690
  st.metric("Words", actual_words)
@@ -692,21 +542,16 @@ def main():
692
  st.metric("Sentences", actual_sentences)
693
  with col_stats3:
694
  st.metric("Paragraphs", paragraphs)
695
-
696
- # Academic quality indicators
697
  st.success("βœ… Document optimized for academic writing")
698
  st.info("πŸ’‘ This thesis is designed to pass AI detection tools and academic scrutiny")
699
  st.warning("⚠️ Remember to review and customize the content for your specific requirements")
700
-
701
- # Remove technical details
702
  st.markdown("---")
703
  st.markdown("### πŸ”’ Privacy & Security")
704
  st.markdown("- Your content is processed securely")
705
  st.markdown("- No data is stored or shared")
706
  st.markdown("- All research is conducted privately")
707
-
708
  else:
709
  st.info("πŸ‘ˆ Enter a thesis topic and click 'Generate Thesis Document' to create your academic content")
710
 
711
  if __name__ == "__main__":
712
- main()
 
2
  import os
3
  import requests
4
  import hashlib
5
+ from typing import List, Dict, Any, Optional, Mapping
6
  from datetime import datetime
7
  import json
8
  import re
 
11
  import random
12
  import markdown
13
 
 
14
  from crewai import Agent, Task, Crew, Process
15
  from crewai.tools import BaseTool
16
  from groq import Groq
 
34
  description: str = "Conduct comprehensive academic research for thesis/synopsis"
35
 
36
  def _run(self, topic: str, research_areas: str) -> str:
 
37
  try:
38
  time.sleep(1)
 
 
39
  search_queries = [
40
  f"{topic} research studies",
41
  f"{topic} academic papers",
 
43
  f"{topic} methodology",
44
  f"{topic} literature review"
45
  ]
 
46
  all_research = []
 
47
  with DDGS() as ddgs:
48
  for query in search_queries:
49
  try:
 
56
  'url': result.get('href', ''),
57
  'relevance_score': self._calculate_relevance(result.get('body', ''), topic)
58
  })
59
+ time.sleep(0.5)
60
+ except Exception:
61
  continue
 
 
62
  unique_research = self._remove_duplicates(all_research)
63
  unique_research.sort(key=lambda x: x['relevance_score'], reverse=True)
64
+ return json.dumps(unique_research[:15])
 
65
  except Exception as e:
66
  return f"Research failed: {str(e)}"
67
 
68
  def _calculate_relevance(self, content: str, topic: str) -> float:
 
69
  topic_words = set(topic.lower().split())
70
  content_words = set(content.lower().split())
 
71
  if not topic_words or not content_words:
72
  return 0.0
 
73
  intersection = topic_words.intersection(content_words)
74
  return len(intersection) / len(topic_words)
75
 
76
  def _remove_duplicates(self, research_list: List[Dict]) -> List[Dict]:
 
77
  seen_urls = set()
78
  unique_research = []
 
79
  for item in research_list:
80
  if item['url'] not in seen_urls:
81
  seen_urls.add(item['url'])
82
  unique_research.append(item)
 
83
  return unique_research
84
 
85
  class CitationGeneratorTool(BaseTool):
 
87
  description: str = "Generate proper academic citations and references"
88
 
89
  def _run(self, research_data: str) -> str:
 
90
  try:
91
  research_items = json.loads(research_data)
92
  citations = []
93
+ for i, item in enumerate(research_items[:10]):
 
 
94
  title = item.get('title', 'Unknown Title')
95
  url = item.get('url', '')
 
 
96
  domain = url.split('/')[2] if len(url.split('/')) > 2 else 'Unknown'
 
97
  citation = {
98
  'id': f"source_{i+1}",
99
  'title': title,
 
103
  'in_text': f"({domain}, {datetime.now().year})"
104
  }
105
  citations.append(citation)
 
106
  return json.dumps(citations)
107
  except Exception as e:
108
  return f"Citation generation failed: {str(e)}"
 
112
  description: str = "Analyze and improve academic writing style"
113
 
114
  def _run(self, text: str, academic_level: str) -> str:
 
115
  try:
 
116
  flesch_score = flesch_reading_ease(text)
117
  fk_grade = flesch_kincaid_grade(text)
 
 
118
  sentences = text.split('.')
119
  sentence_lengths = [len(s.split()) for s in sentences if s.strip()]
120
  avg_sentence_length = sum(sentence_lengths) / max(len(sentence_lengths), 1)
 
 
121
  academic_patterns = [
122
  "furthermore", "moreover", "additionally", "consequently",
123
  "therefore", "thus", "hence", "accordingly", "subsequently"
124
  ]
 
125
  pattern_usage = sum(1 for pattern in academic_patterns if pattern in text.lower())
 
 
126
  level_guidelines = {
127
  'undergraduate': {
128
+ 'target_flesch': (60, 80),
129
+ 'target_grade': (12, 14),
130
+ 'sentence_length': (15, 25)
131
  },
132
  'masters': {
133
+ 'target_flesch': (50, 70),
134
+ 'target_grade': (14, 16),
135
+ 'sentence_length': (18, 30)
136
  },
137
  'phd': {
138
+ 'target_flesch': (40, 60),
139
+ 'target_grade': (16, 18),
140
+ 'sentence_length': (20, 35)
141
  }
142
  }
143
+ guidelines = level_guidelines.get(academic_level.lower(), level_guidelines['masters'])
 
 
144
  analysis = {
145
  'flesch_score': flesch_score,
146
  'fk_grade': fk_grade,
 
149
  'target_guidelines': guidelines,
150
  'suggestions': []
151
  }
 
 
152
  if flesch_score > guidelines['target_flesch'][1]:
153
  analysis['suggestions'].append("Consider more complex sentence structures for academic tone")
154
  if avg_sentence_length < guidelines['sentence_length'][0]:
155
  analysis['suggestions'].append("Use longer, more detailed sentences")
156
  if pattern_usage < 3:
157
  analysis['suggestions'].append("Include more academic transition phrases")
 
158
  return json.dumps(analysis)
159
  except Exception as e:
160
  return f"Academic analysis failed: {str(e)}"
 
164
  description: str = "Make academic writing sound more human and less AI-like"
165
 
166
  def _run(self, text: str) -> str:
 
167
  try:
 
168
  ai_patterns = [
169
  "It is important to note that",
170
  "This demonstrates that",
 
175
  "This implies that",
176
  "It can be concluded that"
177
  ]
 
 
178
  human_alternatives = [
179
  "Notably,",
180
  "This shows",
 
185
  "This implies",
186
  "Therefore,"
187
  ]
 
 
188
  humanized_text = text
189
  for ai_pattern, human_alt in zip(ai_patterns, human_alternatives):
190
  humanized_text = humanized_text.replace(ai_pattern, human_alt)
 
 
191
  variations = [
192
  "Interestingly,",
193
  "Surprisingly,",
 
195
  "Significantly,",
196
  "Importantly,"
197
  ]
 
 
198
  sentences = humanized_text.split('.')
199
+ for i in range(1, len(sentences), 3):
200
  if i < len(sentences) and sentences[i].strip():
201
  variation = random.choice(variations)
202
  sentences[i] = f" {variation} {sentences[i].lstrip()}"
 
203
  humanized_text = '.'.join(sentences)
 
 
204
  personal_insights = [
205
  "Based on the available evidence,",
206
  "From the research findings,",
207
  "Considering the data,",
208
  "In light of these results,"
209
  ]
 
 
210
  if len(sentences) > 5:
211
  insight = random.choice(personal_insights)
212
  sentences[2] = f" {insight} {sentences[2].lstrip()}"
 
213
  return '.'.join(sentences)
214
  except Exception as e:
215
  return f"Humanization failed: {str(e)}"
216
 
 
217
  def rate_limit_handler(max_retries=3, base_delay=2):
218
  def decorator(func):
219
  def wrapper(*args, **kwargs):
 
232
  return decorator
233
 
234
  # Custom LLM class for CrewAI with built-in API
 
 
 
235
  import litellm
236
+ from langchain.llms.base import LLM
237
 
238
  class BuiltInLLM(LLM):
239
  model_name: str = "groq/llama-3.3-70b-versatile"
240
+ api_key: str = "API_KEY" # <-- Replace with your actual API key
241
+
242
  def __init__(self):
243
  super().__init__()
 
 
244
  os.environ["GROQ_API_KEY"] = self.api_key
245
  litellm.set_verbose = False
246
 
 
250
 
251
  @rate_limit_handler(max_retries=3, base_delay=2)
252
  def _call(self, prompt: str, stop: Optional[List[str]] = None, **kwargs) -> str:
 
253
  try:
 
254
  if len(prompt.split()) > 1500:
255
  words = prompt.split()
256
  prompt = ' '.join(words[:1500]) + "..."
 
257
  response = litellm.completion(
258
  model=self.model_name,
259
  messages=[
 
261
  {"role": "user", "content": prompt}
262
  ],
263
  max_tokens=2500,
264
+ temperature=0.6,
265
  top_p=0.9,
266
  api_key=self.api_key
267
  )
 
268
  time.sleep(2)
269
  return response.choices[0].message.content
270
  except Exception as e:
 
275
  def _identifying_params(self) -> Mapping[str, Any]:
276
  return {"model_name": self.model_name}
277
 
 
278
  def create_thesis_agents(llm):
 
 
 
279
  research_agent = Agent(
280
  role="Academic Research Specialist",
281
  goal="Conduct comprehensive academic research and gather credible sources",
 
285
  allow_delegation=False,
286
  llm=llm
287
  )
 
 
288
  thesis_writer = Agent(
289
  role="Academic Thesis Writer",
290
  goal="Write sophisticated thesis documents that sound completely human-written",
 
294
  allow_delegation=False,
295
  llm=llm
296
  )
 
 
297
  humanization_agent = Agent(
298
  role="Academic Writing Humanizer",
299
  goal="Make academic writing sound completely human and undetectable",
 
303
  allow_delegation=False,
304
  llm=llm
305
  )
 
306
  return research_agent, thesis_writer, humanization_agent
307
 
308
  def create_thesis_tasks(topic, document_type, academic_level, research_areas, word_count, agents):
 
309
  research_agent, thesis_writer, humanization_agent = agents
 
 
310
  research_task = Task(
311
  description=f"""
312
  Conduct comprehensive academic research for a {document_type} on "{topic}".
 
313
  Research Areas: {research_areas}
314
  Academic Level: {academic_level}
315
  Target Length: {word_count} words
 
316
  Requirements:
317
  - Find 10-15 credible academic sources
318
  - Gather recent research and developments
 
320
  - Note different perspectives and debates
321
  - Focus on peer-reviewed and scholarly sources
322
  - Include both theoretical and practical aspects
 
323
  Provide a detailed research summary with key findings, methodologies, and source analysis.
324
  """,
325
  agent=research_agent,
326
  expected_output="Comprehensive research summary with credible sources and key insights"
327
  )
 
 
328
  thesis_task = Task(
329
  description=f"""
330
  Write a complete {document_type} on "{topic}" that sounds completely human-written.
 
331
  Academic Level: {academic_level}
332
  Target Length: {word_count} words
333
  Research Areas: {research_areas}
 
334
  Requirements:
335
  - Use the comprehensive research provided
336
  - Write in proper academic style for {academic_level} level
 
342
  - Avoid AI-like patterns and formal robotic language
343
  - Include methodology, findings, and implications
344
  - Make it engaging and intellectually rigorous
 
345
  Structure:
346
  1. Introduction and background
347
  2. Literature review
 
349
  4. Analysis and findings
350
  5. Discussion and implications
351
  6. Conclusion and recommendations
 
352
  Important: Write as if you're a human academic expert sharing original research and insights.
353
  """,
354
  agent=thesis_writer,
355
  expected_output="Complete academic thesis document with proper structure and citations",
356
  dependencies=[research_task]
357
  )
 
 
358
  humanization_task = Task(
359
  description=f"""
360
  Polish and humanize the thesis document to make it completely undetectable as AI-written.
 
361
  Requirements:
362
  - Remove any remaining AI patterns
363
  - Improve natural academic flow
 
369
  - Improve readability without losing sophistication
370
  - Ensure proper citation integration
371
  - Make it sound like expert human academic writing
 
372
  Focus on making it indistinguishable from high-quality human academic writing.
373
  """,
374
  agent=humanization_agent,
375
  expected_output="Final polished human-sounding academic thesis document",
376
  dependencies=[thesis_task]
377
  )
 
378
  return [research_task, thesis_task, humanization_task]
379
 
380
  def run_thesis_writer(topic, document_type, academic_level, research_areas, word_count):
 
381
  try:
 
382
  llm = BuiltInLLM()
 
 
383
  agents = create_thesis_agents(llm)
 
 
384
  tasks = create_thesis_tasks(topic, document_type, academic_level, research_areas, word_count, agents)
 
 
385
  crew = Crew(
386
  agents=list(agents),
387
  tasks=tasks,
388
  process=Process.sequential,
389
  verbose=True
390
  )
 
 
391
  with st.spinner("Creating comprehensive thesis document with AI agents..."):
392
  result = crew.kickoff()
 
393
  return result
394
  except Exception as e:
395
  st.error(f"Error in thesis writing: {str(e)}")
396
  return None
397
 
 
398
  def main():
399
  st.set_page_config(
400
  page_title="Thesis Writer Bot - Academic Document Creator",
401
  page_icon="πŸŽ“",
402
  layout="wide"
403
  )
 
404
  st.title("πŸŽ“ Thesis Writer Bot")
405
  st.markdown("*Create sophisticated, human-like thesis and synopsis documents that pass any AI detection*")
 
 
406
  with st.sidebar:
407
  st.header("ℹ️ About")
 
408
  st.success("βœ… Ready to generate your thesis!")
 
409
  st.markdown("---")
410
  st.markdown("### 🎯 What This Tool Does")
411
  st.markdown("- Creates original, human-like thesis documents")
 
413
  st.markdown("- Generates proper citations and references")
414
  st.markdown("- Ensures content passes AI detection")
415
  st.markdown("- No plagiarism - completely original content")
 
416
  st.markdown("---")
417
  st.markdown("### πŸ“š Document Types")
418
  st.markdown("- **Thesis**: Complete research thesis")
 
420
  st.markdown("- **Dissertation**: PhD-level document")
421
  st.markdown("- **Research Paper**: Academic paper")
422
  st.markdown("- **Literature Review**: Comprehensive review")
 
423
  st.markdown("---")
424
  st.markdown("### πŸŽ“ Academic Levels")
425
  st.markdown("- **Undergraduate**: Bachelor's level")
426
  st.markdown("- **Masters**: Graduate level")
427
  st.markdown("- **PhD**: Doctoral level")
 
428
  st.markdown("---")
429
  st.markdown("### πŸ”₯ Features")
430
  st.markdown("- **No Plagiarism**: Original research")
 
433
  st.markdown("- **Proper Citations**: Academic references")
434
  st.markdown("- **Research-based**: Credible sources")
435
  st.markdown("- **No Word Limits**: Any length needed")
 
 
436
  col1, col2 = st.columns([1, 1])
 
437
  with col1:
438
  st.header("πŸ“ Thesis Request")
 
 
439
  topic = st.text_input(
440
  "What is your thesis/synopsis topic?",
441
  placeholder="e.g., Impact of artificial intelligence on healthcare delivery systems"
442
  )
 
 
443
  document_types = [
444
  "Thesis", "Synopsis", "Dissertation", "Research Paper",
445
  "Literature Review", "Research Proposal", "Academic Report"
446
  ]
447
  document_type = st.selectbox("Document Type", document_types)
 
 
448
  academic_levels = ["Undergraduate", "Masters", "PhD"]
449
  academic_level = st.selectbox("Academic Level", academic_levels)
 
 
450
  research_areas = st.text_area(
451
  "Specific Research Areas/Focus (Optional)",
452
  placeholder="e.g., methodology, recent developments, case studies, theoretical frameworks...",
453
  height=80
454
  )
 
 
455
  word_count = st.number_input(
456
  "Target Word Count",
457
  min_value=1000,
 
460
  step=500,
461
  help="No strict limit - write as much as needed"
462
  )
 
 
463
  additional_requirements = st.text_area(
464
  "Additional Requirements (Optional)",
465
  placeholder="Specific methodology, theoretical framework, case studies, etc...",
466
  height=100
467
  )
 
 
468
  if st.button("πŸš€ Generate Thesis Document", type="primary", use_container_width=True):
469
  if not topic.strip():
470
  st.error("Please enter a thesis topic!")
471
  else:
 
472
  research_areas_text = research_areas if research_areas.strip() else "general academic research"
 
 
473
  result = run_thesis_writer(topic, document_type, academic_level, research_areas_text, word_count)
 
474
  if result:
475
  st.session_state.generated_thesis = result
476
  st.session_state.thesis_info = {
 
482
  'requirements': additional_requirements
483
  }
484
  st.success("βœ… Thesis document generated successfully!")
 
485
  with col2:
486
  st.header("πŸ“„ Generated Thesis")
 
487
  if "generated_thesis" in st.session_state:
488
  thesis = st.session_state.generated_thesis
489
  info = st.session_state.thesis_info
 
 
490
  st.subheader("πŸ“Š Document Information")
491
  col_info1, col_info2 = st.columns(2)
492
  with col_info1:
 
497
  st.metric("Generated Words", len(str(thesis).split()))
498
  st.metric("Research Areas", info['research_areas'][:20] + "..." if len(info['research_areas']) > 20 else info['research_areas'])
499
  st.metric("Quality", "βœ… Human-like")
 
 
500
  st.subheader("πŸ“ Your Thesis Document")
 
 
501
  formatted_thesis = str(thesis)
 
502
  st.text_area(
503
  "Generated Thesis:",
504
  value=formatted_thesis,
505
  height=400,
506
  help="This is your human-like thesis document"
507
  )
 
 
508
  col_dl1, col_dl2 = st.columns(2)
509
  with col_dl1:
510
  st.download_button(
 
513
  file_name=f"{info['topic'].replace(' ', '_')}_{info['type']}.txt",
514
  mime="text/plain"
515
  )
 
516
  with col_dl2:
 
517
  markdown_content = f"""# {info['topic']}
 
518
  **Document Type:** {info['type']}
519
  **Academic Level:** {info['level']}
520
  **Research Areas:** {info['research_areas']}
521
  **Word Count:** {len(str(thesis).split())}
522
  **Generated:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
 
523
  ---
 
524
  {formatted_thesis}
 
525
  ---
 
526
  *This document was generated using advanced AI technology and is designed to be indistinguishable from human academic writing.*
527
  """
528
  st.download_button(
 
531
  file_name=f"{info['topic'].replace(' ', '_')}_{info['type']}.md",
532
  mime="text/markdown"
533
  )
 
 
534
  st.subheader("πŸ” Document Analysis")
 
 
535
  actual_words = len(str(thesis).split())
536
  actual_sentences = len(str(thesis).split('.'))
537
  paragraphs = len(str(thesis).split('\n\n'))
 
538
  col_stats1, col_stats2, col_stats3 = st.columns(3)
539
  with col_stats1:
540
  st.metric("Words", actual_words)
 
542
  st.metric("Sentences", actual_sentences)
543
  with col_stats3:
544
  st.metric("Paragraphs", paragraphs)
 
 
545
  st.success("βœ… Document optimized for academic writing")
546
  st.info("πŸ’‘ This thesis is designed to pass AI detection tools and academic scrutiny")
547
  st.warning("⚠️ Remember to review and customize the content for your specific requirements")
 
 
548
  st.markdown("---")
549
  st.markdown("### πŸ”’ Privacy & Security")
550
  st.markdown("- Your content is processed securely")
551
  st.markdown("- No data is stored or shared")
552
  st.markdown("- All research is conducted privately")
 
553
  else:
554
  st.info("πŸ‘ˆ Enter a thesis topic and click 'Generate Thesis Document' to create your academic content")
555
 
556
  if __name__ == "__main__":
557
+ main()