-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
1882 lines (1517 loc) · 73.9 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import json
import os
import re
import random
import base64
import requests
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QPushButton, QLabel, QComboBox, QTextEdit, QLineEdit,
QTabWidget, QGridLayout, QScrollArea, QFrame, QMessageBox,
QGroupBox, QRadioButton, QButtonGroup, QInputDialog, QDialog,
QFormLayout, QDialogButtonBox, QCheckBox, QSplitter, QListWidget,
QListWidgetItem, QProgressBar, QToolTip, QPlainTextEdit, QProgressDialog,
QFileDialog, QSizePolicy, QSpacerItem)
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QSize, QUrl, QTimer, QByteArray
from PyQt5.QtGui import QPixmap, QFont, QImage, QDesktopServices, QClipboard, QColor, QTextCharFormat, QTextCursor, QIcon
import google.generativeai as genai
from io import BytesIO
import time
import urllib.request
import webbrowser
import html
# App version and information
APP_VERSION = "1.2.0"
APP_NAME = "AI Article Generator for Medium"
APP_FEATURES = [
"Generate high-quality articles with Gemini AI",
"Optimize content for Medium's platform",
"Search and add Unsplash images",
"Manage article tags for better discoverability",
"Check article quality with built-in analyzer",
"Preview articles in Medium-like interface",
"One-click publishing to Medium"
]
# Mock data for demonstration
TRENDING_TOPICS = [
"Artificial Intelligence in Healthcare",
"Remote Work Best Practices",
"Sustainable Living Tips",
"Cryptocurrency Market Analysis",
"Mental Health in the Workplace",
"Future of Electric Vehicles",
"Digital Marketing Strategies",
"Personal Finance Management",
"Climate Change Solutions",
"Productivity Tools for 2025"
]
NICHES = [
"Technology",
"Health & Wellness",
"Finance",
"Marketing",
"Productivity",
"Artificial Intelligence",
"Programming",
"Design"
]
# Medium tags by category
MEDIUM_TAGS = {
"Technology": ["technology", "tech", "programming", "software", "data-science", "machine-learning", "artificial-intelligence"],
"Health & Wellness": ["health", "wellness", "mental-health", "fitness", "nutrition", "self-care", "mindfulness"],
"Finance": ["finance", "money", "investing", "cryptocurrency", "personal-finance", "economics", "business"],
"Marketing": ["marketing", "digital-marketing", "social-media", "content-marketing", "seo", "branding", "growth"],
"Productivity": ["productivity", "self-improvement", "life-lessons", "life-hacks", "organization", "time-management"],
"Artificial Intelligence": ["artificial-intelligence", "machine-learning", "deep-learning", "ai", "data-science", "neural-networks"],
"Programming": ["programming", "software-development", "coding", "javascript", "python", "web-development", "technology"],
"Design": ["design", "ux", "ui", "user-experience", "product-design", "creativity", "visual-design"]
}
# Default author bio
DEFAULT_AUTHOR_BIO = """Mr Mizoku
Tech enthusiast, writer, and digital creator exploring the worlds of innovation, AI, and entrepreneurship. Passionate about building digital products and sharing insights on technology, business, and creativity."""
# Article quality checklist
ARTICLE_QUALITY_CHECKLIST = [
"Engaging Title – Catchy, clear, and relevant to your audience",
"Strong Introduction – Hook the reader in the first few lines",
"Well-Structured Content – Use headings, subheadings, and short paragraphs",
"Valuable Insights – Provide useful, original, or well-researched information",
"SEO Optimization – Use relevant keywords naturally",
"Images & Formatting – Add visuals, bullet points, and bold/italic text",
"Call to Action (CTA) – Encourage engagement (comments, shares, subscriptions)",
"Proofreading & Editing – Ensure grammar, spelling, and clarity are perfect",
"Tags & Metadata – Use relevant Medium tags for discoverability",
"Author Bio – A short, relevant bio to establish credibility"
]
class BrandingWindow(QDialog):
def __init__(self, parent=None, has_api_key=False):
super().__init__(parent)
self.setWindowTitle(APP_NAME)
self.resize(600, 500)
self.setWindowFlags(Qt.Dialog | Qt.CustomizeWindowHint | Qt.WindowTitleHint)
self.has_api_key = has_api_key
# Main layout
layout = QVBoxLayout(self)
layout.setSpacing(20)
layout.setContentsMargins(30, 30, 30, 30)
# App icon
icon_layout = QHBoxLayout()
icon_label = QLabel()
icon_path = os.path.join("assets", "android-chrome-192x192.png")
if os.path.exists(icon_path):
pixmap = QPixmap(icon_path)
icon_label.setPixmap(pixmap.scaled(128, 128, Qt.KeepAspectRatio, Qt.SmoothTransformation))
else:
icon_label.setText("Icon not found")
icon_layout.addStretch()
icon_layout.addWidget(icon_label)
icon_layout.addStretch()
layout.addLayout(icon_layout)
# App name and version
title_label = QLabel(APP_NAME)
title_font = QFont()
title_font.setPointSize(18)
title_font.setBold(True)
title_label.setFont(title_font)
title_label.setAlignment(Qt.AlignCenter)
layout.addWidget(title_label)
version_label = QLabel(f"Version {APP_VERSION}")
version_label.setAlignment(Qt.AlignCenter)
layout.addWidget(version_label)
# Separator
separator = QFrame()
separator.setFrameShape(QFrame.HLine)
separator.setFrameShadow(QFrame.Sunken)
layout.addWidget(separator)
# Features
features_group = QGroupBox("Key Features")
features_layout = QVBoxLayout()
for feature in APP_FEATURES:
feature_label = QLabel(f"• {feature}")
features_layout.addWidget(feature_label)
features_group.setLayout(features_layout)
layout.addWidget(features_group)
# API key message
if not has_api_key:
api_message = QLabel("You need to set up your Google Gemini API key to use this application.")
api_message.setStyleSheet("color: #e74c3c; font-weight: bold;")
api_message.setAlignment(Qt.AlignCenter)
layout.addWidget(api_message)
# Buttons
button_layout = QHBoxLayout()
if not has_api_key:
setup_api_btn = QPushButton("Set Up API Key")
setup_api_btn.clicked.connect(self.accept)
button_layout.addWidget(setup_api_btn)
else:
start_btn = QPushButton("Start Using App")
start_btn.clicked.connect(self.accept)
button_layout.addWidget(start_btn)
layout.addLayout(button_layout)
# Copyright
copyright_label = QLabel("© 2025 AI Article Generator. All rights reserved.")
copyright_label.setAlignment(Qt.AlignCenter)
copyright_label.setStyleSheet("color: #7f8c8d; font-size: 10px;")
layout.addWidget(copyright_label)
class GenerateArticleThread(QThread):
finished = pyqtSignal(dict)
error = pyqtSignal(str)
progress = pyqtSignal(int)
def __init__(self, topic, niche, api_key, medium_format=True, author_bio=DEFAULT_AUTHOR_BIO):
super().__init__()
self.topic = topic
self.niche = niche
self.api_key = api_key
self.medium_format = medium_format
self.author_bio = author_bio
def run(self):
try:
# Emit initial progress
self.progress.emit(5)
# Configure the Gemini API
genai.configure(api_key=self.api_key)
model = genai.GenerativeModel('gemini-1.5-pro')
# Emit progress update
self.progress.emit(15)
# Create a prompt that specifically requests Medium-compatible formatting
if self.medium_format:
prompt = f"""
Write a professional, well-structured article about "{self.topic}" for the "{self.niche}" niche that is ready to be directly pasted into Medium's editor.
IMPORTANT REQUIREMENTS:
1. The article MUST be at least 1000 words in length, preferably between 1200-2000 words
2. Use CLEAR, DISTINCT SUBHEADINGS to organize the content (at least 4-5 subheadings)
3. Include BULLET POINTS to highlight key information
4. Break long sentences into shorter ones for better readability (max 20 words per sentence)
5. Use SHORT PARAGRAPHS (2-3 sentences maximum per paragraph)
6. HIGHLIGHT KEY INFORMATION by using clear, concise statements
7. Format for Medium's editor (no markdown, just plain text)
The article MUST include:
1. An engaging, catchy title that's clear and relevant to the audience
2. A strong introduction that hooks the reader in the first few lines
3. Well-structured content with clear headings, subheadings, and short paragraphs for readability
4. Valuable insights that provide useful, original, or well-researched information
5. Naturally incorporated relevant keywords for SEO optimization
6. Bullet points to highlight key information
7. A clear call to action (CTA) at the end encouraging reader engagement (comments, shares, or subscriptions)
End the article with this author bio:
---
{self.author_bio}
---
Return the response in the following format:
TITLE: [Your title here]
CONTENT:
[Your article content here with Medium-compatible formatting]
TAGS: [Suggest 5 relevant tags for this article on Medium, separated by commas]
"""
else:
# Original prompt with markdown formatting
prompt = f"""
Write a professional, well-structured article about "{self.topic}" for the "{self.niche}" niche.
IMPORTANT REQUIREMENTS:
1. The article MUST be at least 1000 words in length, preferably between 1200-2000 words
2. Use CLEAR, DISTINCT SUBHEADINGS to organize the content (at least 4-5 subheadings)
3. Include BULLET POINTS to highlight key information
4. Break long sentences into shorter ones for better readability (max 20 words per sentence)
5. Use SHORT PARAGRAPHS (2-3 sentences maximum per paragraph)
6. HIGHLIGHT KEY INFORMATION by using clear, concise statements
The article should:
1. Have an engaging title
2. Include an introduction that hooks the reader
3. Have clear subheadings for each section
4. Include bullet points or numbered lists where appropriate
5. Have a conclusion that summarizes the main points
6. Include actionable advice or insights
7. End with a call to action
8. Include the author bio at the end
End the article with this author bio:
---
{self.author_bio}
---
Return the response in the following format:
TITLE: [Your title here]
CONTENT:
[Your article content here with proper formatting]
TAGS: [Suggest 5 relevant tags for this article on Medium, separated by commas]
"""
# Emit progress update
self.progress.emit(25)
# Generate the article
response = model.generate_content(prompt)
# Emit progress update
self.progress.emit(75)
response_text = response.text
# Parse the response text into title, content, and tags
try:
# Extract title
title_match = re.search(r'TITLE:(.*?)(?=CONTENT:|$)', response_text, re.DOTALL)
title = title_match.group(1).strip() if title_match else ""
# Extract content
content_match = re.search(r'CONTENT:(.*?)(?=TAGS:|$)', response_text, re.DOTALL)
content = content_match.group(1).strip() if content_match else ""
# Extract tags
tags_match = re.search(r'TAGS:(.*?)$', response_text, re.DOTALL)
tags = tags_match.group(1).strip() if tags_match else ""
# If Medium format is requested, ensure the content is properly formatted
if self.medium_format:
content = self.format_for_medium(content)
# Post-process the content to ensure readability
content = self.improve_readability(content)
# Check word count and regenerate if needed
word_count = len(content.split())
if word_count < 1000:
self.progress.emit(80)
# Regenerate with stronger emphasis on length
prompt = prompt.replace("at least 1000 words", "at least 1200 words")
prompt = prompt.replace("preferably between 1200-2000", "MUST be at least 1200 words")
response = model.generate_content(prompt)
response_text = response.text
# Re-extract content
content_match = re.search(r'CONTENT:(.*?)(?=TAGS:|$)', response_text, re.DOTALL)
content = content_match.group(1).strip() if content_match else ""
# Re-format and improve
if self.medium_format:
content = self.format_for_medium(content)
content = self.improve_readability(content)
# Emit progress update
self.progress.emit(90)
result = {
"title": title,
"content": content,
"tags": [tag.strip() for tag in tags.split(',')]
}
# Emit progress update
self.progress.emit(100)
self.finished.emit(result)
except Exception as parse_error:
raise Exception(f"Failed to parse article structure: {str(parse_error)}")
except Exception as e:
self.error.emit(str(e))
def format_for_medium(self, content):
"""
Ensure the content is properly formatted for Medium's editor
This removes any markdown or special formatting that doesn't work in Medium
"""
# Remove markdown heading markers (##, ###, etc.)
content = re.sub(r'^#+\s+', '', content, flags=re.MULTILINE)
# Remove markdown bold/italic markers (**, *)
content = re.sub(r'\*\*(.*?)\*\*', r'\1', content)
content = re.sub(r'\*(.*?)\*', r'\1', content)
# Replace markdown links with plain text
content = re.sub(r'\[(.*?)\]$$(.*?)$$', r'\1 (\2)', content)
# Replace markdown list items with simple bullets or numbers
content = re.sub(r'^\s*[-*]\s+', '• ', content, flags=re.MULTILINE)
# Ensure proper spacing between paragraphs (Medium likes double line breaks)
content = re.sub(r'\n\s*\n', '\n\n', content)
content = re.sub(r'\n{3,}', '\n\n', content)
return content
def improve_readability(self, content):
"""
Improve the readability of the content by:
1. Breaking long sentences
2. Ensuring paragraphs are short
"""
# Split content into paragraphs
paragraphs = content.split('\n\n')
improved_paragraphs = []
for paragraph in paragraphs:
# Skip headings and bullet points
if len(paragraph.strip()) < 60 or paragraph.strip().startswith('•'):
improved_paragraphs.append(paragraph)
continue
# Break long sentences (more than 25 words)
sentences = re.split(r'(?<=[.!?])\s+', paragraph)
improved_sentences = []
for sentence in sentences:
words = sentence.split()
if len(words) > 25:
# Find a good breaking point around the middle
mid_point = len(words) // 2
# Look for conjunctions or commas near the midpoint
break_point = None
# Search for conjunctions or commas near the midpoint
for i in range(max(5, mid_point - 5), min(len(words) - 5, mid_point + 5)):
if words[i].lower() in ['and', 'but', 'or', 'because', 'however', 'therefore']:
break_point = i
break
elif words[i].endswith(','):
break_point = i
break
if break_point:
# Split the sentence at the break point
first_half = ' '.join(words[:break_point + 1])
second_half = ' '.join(words[break_point + 1:])
improved_sentences.append(first_half)
improved_sentences.append(second_half)
else:
improved_sentences.append(sentence)
else:
improved_sentences.append(sentence)
# Combine sentences back into a paragraph
improved_paragraph = ' '.join(improved_sentences)
# Break long paragraphs into shorter ones (more than 3 sentences)
if len(improved_sentences) > 3:
# Create smaller paragraphs of 2-3 sentences
for i in range(0, len(improved_sentences), 2):
if i + 2 <= len(improved_sentences):
small_paragraph = ' '.join(improved_sentences[i:i+2])
improved_paragraphs.append(small_paragraph)
else:
small_paragraph = ' '.join(improved_sentences[i:])
improved_paragraphs.append(small_paragraph)
else:
improved_paragraphs.append(improved_paragraph)
# Combine paragraphs back into content
improved_content = '\n\n'.join(improved_paragraphs)
return improved_content
class UnsplashImageSearchThread(QThread):
finished = pyqtSignal(list)
error = pyqtSignal(str)
def __init__(self, query, access_key=None):
super().__init__()
self.query = query
self.access_key = access_key
def run(self):
try:
if self.access_key:
# Use Unsplash API if access key is provided
url = f"https://api.unsplash.com/search/photos?query={self.query}&per_page=10"
headers = {"Authorization": f"Client-ID {self.access_key}"}
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
images = []
for item in data.get("results", []):
images.append({
"url": item["urls"]["regular"],
"download_url": item["links"]["download"],
"author": item["user"]["name"],
"author_url": item["user"]["links"]["html"]
})
self.finished.emit(images)
else:
# Fallback to placeholder images
self.use_placeholder_images()
else:
# Use placeholder images if no access key
self.use_placeholder_images()
except Exception as e:
self.error.emit(str(e))
def use_placeholder_images(self):
# Using Lorem Picsum for placeholder images
mock_images = []
for i in range(6):
url = f"https://picsum.photos/seed/{hash(self.query + str(i))}/400/300"
mock_images.append({
"url": url,
"download_url": url,
"author": "Lorem Picsum",
"author_url": "https://picsum.photos/"
})
time.sleep(1) # Simulate API delay
self.finished.emit(mock_images)
class SearchImagesThread(QThread):
finished = pyqtSignal(list)
error = pyqtSignal(str)
def __init__(self, query):
super().__init__()
self.query = query
def run(self):
try:
# Using Lorem Picsum for placeholder images
mock_images = []
for i in range(6):
url = f"https://picsum.photos/seed/{hash(self.query + str(i))}/400/300"
mock_images.append(url)
time.sleep(1) # Simulate API delay
self.finished.emit(mock_images)
except Exception as e:
self.error.emit(str(e))
class ArticleQualityCheckerThread(QThread):
finished = pyqtSignal(dict)
progress = pyqtSignal(int, str)
def __init__(self, title, content, tags):
super().__init__()
self.title = title
self.content = content
self.tags = tags
def run(self):
results = {
"score": 0,
"max_score": 100,
"feedback": [],
"improvements": []
}
# Check title
self.progress.emit(10, "Checking title...")
if len(self.title) < 5:
results["feedback"].append("Title is too short")
results["improvements"].append("Create a more engaging title (aim for 6-10 words)")
elif len(self.title) > 60:
results["feedback"].append("Title is too long")
results["improvements"].append("Shorten your title to be more impactful (under 60 characters)")
else:
results["score"] += 10
# Check introduction
self.progress.emit(20, "Analyzing introduction...")
intro = self.content.split('\n\n')[0] if '\n\n' in self.content else self.content[:300]
if len(intro) < 100:
results["feedback"].append("Introduction may be too short")
results["improvements"].append("Expand your introduction to hook readers (150-200 words)")
else:
results["score"] += 10
# Check structure
self.progress.emit(30, "Checking structure...")
paragraphs = self.content.split('\n\n')
if len(paragraphs) < 5:
results["feedback"].append("Article may need more structure")
results["improvements"].append("Add more paragraphs and subheadings for better readability")
else:
results["score"] += 10
# Check for headings
potential_headings = [p for p in paragraphs if len(p.split('\n')) == 1 and len(p) < 80 and p.strip() and not p.startswith('•')]
if len(potential_headings) < 3:
results["feedback"].append("Article may need more headings")
results["improvements"].append("Add clear subheadings to organize your content")
else:
results["score"] += 10
# Check for bullet points
self.progress.emit(40, "Checking formatting...")
has_bullets = '•' in self.content
if not has_bullets:
results["feedback"].append("No bullet points detected")
results["improvements"].append("Add bullet points to highlight key information")
else:
results["score"] += 10
# Check for call to action
self.progress.emit(50, "Checking for call to action...")
last_paragraphs = ' '.join(paragraphs[-3:]).lower()
cta_phrases = ['comment', 'share', 'follow', 'subscribe', 'let me know', 'what do you think', 'your thoughts']
has_cta = any(phrase in last_paragraphs for phrase in cta_phrases)
if not has_cta:
results["feedback"].append("No clear call to action detected")
results["improvements"].append("Add a call to action at the end to encourage engagement")
else:
results["score"] += 10
# Check content length
self.progress.emit(60, "Checking content length...")
word_count = len(self.content.split())
if word_count < 1000:
results["feedback"].append(f"Article is too short ({word_count} words)")
results["improvements"].append("Expand your article to at least 1000 words for better engagement")
elif word_count > 2000:
results["feedback"].append(f"Article is very long ({word_count} words)")
results["improvements"].append("Consider shortening to 1000-2000 words for better readability")
else:
results["score"] += 10
# Check for author bio
self.progress.emit(70, "Checking author bio...")
has_bio = "Mr Mizoku" in self.content or "Tech enthusiast" in self.content
if not has_bio:
results["feedback"].append("Author bio may be missing")
results["improvements"].append("Add your author bio at the end of the article")
else:
results["score"] += 10
# Check tags
self.progress.emit(80, "Checking tags...")
if not self.tags or len(self.tags) < 3:
results["feedback"].append("Not enough tags")
results["improvements"].append("Add at least 5 relevant tags for better discoverability")
else:
results["score"] += 10
# Check readability (simple implementation)
self.progress.emit(90, "Analyzing readability...")
avg_sentence_length = len(self.content) / (self.content.count('.') + self.content.count('!') + self.content.count('?') + 1)
if avg_sentence_length > 25:
results["feedback"].append("Sentences may be too long")
results["improvements"].append("Break down long sentences for better readability")
else:
results["score"] += 10
# Final check
self.progress.emit(100, "Finalizing analysis...")
# If no issues found in a category, add positive feedback
if not results["feedback"]:
results["feedback"].append("Great job! Your article meets all quality guidelines.")
# Calculate final score
results["score"] = min(100, results["score"] + random.randint(0, 10)) # Add a bit of randomness
self.finished.emit(results)
class SettingsDialog(QDialog):
def __init__(self, parent=None, author_bio=DEFAULT_AUTHOR_BIO, unsplash_key=""):
super().__init__(parent)
self.setWindowTitle("Article Generator Settings")
self.resize(500, 400)
layout = QVBoxLayout(self)
# API Settings Group
api_group = QGroupBox("API Settings")
api_layout = QFormLayout()
# Gemini API Key
self.gemini_input = QLineEdit()
self.gemini_input.setEchoMode(QLineEdit.Password)
api_layout.addRow("Google Gemini API Key:", self.gemini_input)
# Unsplash API Key
self.unsplash_input = QLineEdit()
self.unsplash_input.setEchoMode(QLineEdit.Password)
self.unsplash_input.setText(unsplash_key)
api_layout.addRow("Unsplash Access Key:", self.unsplash_input)
api_group.setLayout(api_layout)
layout.addWidget(api_group)
# Author Bio Group
bio_group = QGroupBox("Author Bio")
bio_layout = QVBoxLayout()
bio_label = QLabel("Your author bio will be added to the end of each article:")
bio_layout.addWidget(bio_label)
self.bio_text = QTextEdit()
self.bio_text.setText(author_bio)
bio_layout.addWidget(self.bio_text)
bio_group.setLayout(bio_layout)
layout.addWidget(bio_group)
# Buttons
button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
layout.addWidget(button_box)
def get_values(self):
return {
"gemini_api_key": self.gemini_input.text(),
"author_bio": self.bio_text.toPlainText(),
"unsplash_key": self.unsplash_input.text()
}
class TagSelectionDialog(QDialog):
def __init__(self, parent=None, suggested_tags=None, niche=None):
super().__init__(parent)
self.setWindowTitle("Select Tags for Medium")
self.resize(400, 500)
layout = QVBoxLayout(self)
# Instructions
instructions = QLabel("Select up to 5 tags for your Medium article (recommended for better discoverability):")
layout.addWidget(instructions)
# Suggested tags section
if suggested_tags and len(suggested_tags) > 0:
suggested_group = QGroupBox("Suggested Tags")
suggested_layout = QVBoxLayout()
self.suggested_checks = []
for tag in suggested_tags:
check = QCheckBox(tag)
check.setChecked(True) # Default to checked
self.suggested_checks.append(check)
suggested_layout.addWidget(check)
suggested_group.setLayout(suggested_layout)
layout.addWidget(suggested_group)
# Popular tags by category
if niche and niche in MEDIUM_TAGS:
popular_group = QGroupBox(f"Popular {niche} Tags")
popular_layout = QVBoxLayout()
self.popular_checks = []
for tag in MEDIUM_TAGS[niche]:
if not suggested_tags or tag not in suggested_tags:
check = QCheckBox(tag)
self.popular_checks.append(check)
popular_layout.addWidget(check)
popular_group.setLayout(popular_layout)
layout.addWidget(popular_group)
# Custom tag
custom_group = QGroupBox("Add Custom Tag")
custom_layout = QHBoxLayout()
self.custom_tag = QLineEdit()
self.custom_tag.setPlaceholderText("Enter a custom tag")
add_btn = QPushButton("Add")
add_btn.clicked.connect(self.add_custom_tag)
custom_layout.addWidget(self.custom_tag)
custom_layout.addWidget(add_btn)
custom_group.setLayout(custom_layout)
layout.addWidget(custom_group)
# Custom tags list
self.custom_list = QListWidget()
layout.addWidget(self.custom_list)
# Selected tags count
self.count_label = QLabel("Selected tags: 0/5")
layout.addWidget(self.count_label)
# Copy tags button
copy_tags_btn = QPushButton("Copy Tags")
copy_tags_btn.clicked.connect(self.copy_tags)
layout.addWidget(copy_tags_btn)
# Connect signals for tag counting
if suggested_tags:
for check in self.suggested_checks:
check.stateChanged.connect(self.update_tag_count)
if niche and niche in MEDIUM_TAGS:
for check in self.popular_checks:
check.stateChanged.connect(self.update_tag_count)
# Update initial count
self.update_tag_count()
# Buttons
button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
layout.addWidget(button_box)
def add_custom_tag(self):
tag = self.custom_tag.text().strip().lower()
if tag:
# Check if already exists
existing_items = [self.custom_list.item(i).text() for i in range(self.custom_list.count())]
if tag not in existing_items:
self.custom_list.addItem(tag)
self.custom_tag.clear()
self.update_tag_count()
def update_tag_count(self):
count = 0
# Count suggested tags
if hasattr(self, 'suggested_checks'):
count += sum(1 for check in self.suggested_checks if check.isChecked())
# Count popular tags
if hasattr(self, 'popular_checks'):
count += sum(1 for check in self.popular_checks if check.isChecked())
# Count custom tags
count += self.custom_list.count()
self.count_label.setText(f"Selected tags: {count}/5")
# Disable checkboxes if we have 5 tags already
if count >= 5:
if hasattr(self, 'suggested_checks'):
for check in self.suggested_checks:
if not check.isChecked():
check.setEnabled(False)
if hasattr(self, 'popular_checks'):
for check in self.popular_checks:
if not check.isChecked():
check.setEnabled(False)
self.custom_tag.setEnabled(False)
else:
if hasattr(self, 'suggested_checks'):
for check in self.suggested_checks:
check.setEnabled(True)
if hasattr(self, 'popular_checks'):
for check in self.popular_checks:
check.setEnabled(True)
self.custom_tag.setEnabled(True)
def get_selected_tags(self):
tags = []
# Get suggested tags
if hasattr(self, 'suggested_checks'):
tags.extend([check.text() for check in self.suggested_checks if check.isChecked()])
# Get popular tags
if hasattr(self, 'popular_checks'):
tags.extend([check.text() for check in self.popular_checks if check.isChecked()])
# Get custom tags
for i in range(self.custom_list.count()):
tags.append(self.custom_list.item(i).text())
# Limit to 5 tags
return tags[:5]
def copy_tags(self):
tags = self.get_selected_tags()
if tags:
clipboard = QApplication.clipboard()
clipboard.setText(", ".join(tags))
QMessageBox.information(self, "Tags Copied", "Tags have been copied to clipboard.")
else:
QMessageBox.warning(self, "No Tags Selected", "Please select at least one tag to copy.")
class ArticleQualityDialog(QDialog):
def __init__(self, parent=None, title="", content="", tags=None):
super().__init__(parent)
self.setWindowTitle("Article Quality Check")
self.resize(600, 500)
self.title = title
self.content = content
self.tags = tags or []
layout = QVBoxLayout(self)
# Progress section
progress_layout = QHBoxLayout()
self.progress_bar = QProgressBar()
self.progress_bar.setRange(0, 100)
self.progress_bar.setValue(0)
self.status_label = QLabel("Analyzing article quality...")
progress_layout.addWidget(self.progress_bar)
progress_layout.addWidget(self.status_label)
layout.addLayout(progress_layout)
# Results section
results_group = QGroupBox("Quality Analysis Results")
results_layout = QVBoxLayout()
self.score_label = QLabel("Article Quality Score: Analyzing...")
self.score_label.setAlignment(Qt.AlignCenter)
score_font = QFont()
score_font.setPointSize(14)
score_font.setBold(True)
self.score_label.setFont(score_font)
results_layout.addWidget(self.score_label)
# Feedback section
feedback_label = QLabel("Feedback:")
results_layout.addWidget(feedback_label)
self.feedback_list = QListWidget()
results_layout.addWidget(self.feedback_list)
# Improvements section
improvements_label = QLabel("Suggested Improvements:")
results_layout.addWidget(improvements_label)
self.improvements_list = QListWidget()
results_layout.addWidget(self.improvements_list)
results_group.setLayout(results_layout)
layout.addWidget(results_group)
# Checklist section
checklist_group = QGroupBox("Medium Publishing Checklist")
checklist_layout = QVBoxLayout()
self.checklist = QListWidget()
for item in ARTICLE_QUALITY_CHECKLIST:
list_item = QListWidgetItem(item)
list_item.setFlags(list_item.flags() | Qt.ItemIsUserCheckable)
list_item.setCheckState(Qt.Unchecked)
self.checklist.addItem(list_item)
checklist_layout.addWidget(self.checklist)
checklist_group.setLayout(checklist_layout)
layout.addWidget(checklist_group)
# Buttons
button_layout = QHBoxLayout()
self.analyze_btn = QPushButton("Re-Analyze")
self.analyze_btn.clicked.connect(self.start_analysis)
close_btn = QPushButton("Close")
close_btn.clicked.connect(self.accept)
button_layout.addWidget(self.analyze_btn)
button_layout.addWidget(close_btn)
layout.addLayout(button_layout)
# Start analysis
self.start_analysis()
def start_analysis(self):
# Reset UI
self.progress_bar.setValue(0)
self.status_label.setText("Analyzing article quality...")
self.score_label.setText("Article Quality Score: Analyzing...")
self.feedback_list.clear()
self.improvements_list.clear()
# Disable analyze button during analysis
self.analyze_btn.setEnabled(False)
# Start analysis thread
self.analysis_thread = ArticleQualityCheckerThread(self.title, self.content, self.tags)
self.analysis_thread.progress.connect(self.update_progress)
self.analysis_thread.finished.connect(self.show_results)
self.analysis_thread.start()
def update_progress(self, value, status):
self.progress_bar.setValue(value)
self.status_label.setText(status)
def show_results(self, results):
# Update score
score = results["score"]
self.score_label.setText(f"Article Quality Score: {score}/100")
# Set score color based on value
if score >= 80:
self.score_label.setStyleSheet("color: green;")
elif score >= 60:
self.score_label.setStyleSheet("color: orange;")
else:
self.score_label.setStyleSheet("color: red;")
# Update feedback list
for feedback in results["feedback"]:
self.feedback_list.addItem(feedback)
# Update improvements list
for improvement in results["improvements"]:
self.improvements_list.addItem(improvement)
# Auto-check items in the checklist based on analysis
self.update_checklist(results)
# Re-enable analyze button
self.analyze_btn.setEnabled(True)
def update_checklist(self, results):
# Map feedback to checklist items
feedback_lower = [f.lower() for f in results["feedback"]]
# Check each item based on feedback
for i in range(self.checklist.count()):
item = self.checklist.item(i)
text_lower = item.text().lower()
# Default to checked unless we have specific feedback indicating an issue
should_check = True