Kaynak kod içeriğinde makaleye göre otomatik resimde indirme mevcut. Ayrıca belirleyeceğiniz bir şablonun üzerine makale başlığını otomatik kendisi yazıyor. Ayrıca h1 ve keywordleri bold olarak otomatik hallediyor.
Umarım faydalı olur

private static readonly string OpenAiApiKey = "";
private static readonly string PexelsApiKey = "";
public static string keywords = "";
public static string subject = "";
public static async Task Main(string[] args)
{
Console.WriteLine("Enter the subject: ");
subject = Console.ReadLine();
Console.WriteLine("Enter the keywords: ");
keywords = Console.ReadLine();
Console.WriteLine("Enter the image keywords: ");
string imageKeywords = Console.ReadLine();
var usedImages = LoadUsedImages();
await GenerateAndSaveArticle(subject, keywords, imageKeywords, usedImages);
SaveUsedImages(usedImages);
}
public static async Task GenerateAndSaveArticle(string subject, string keywords, string imageKeywords, HashSet<string> usedImages)
{
Console.WriteLine($"Writing main article for subject: {subject}");
// Generate main article prompt and get response
string mainPrompt = GeneratePrompt(subject, true, keywords);
string mainArticle = await GetGpt3Response(mainPrompt);
// Create folder for the subject
CreateFolder(subject);
// Save main article to the folder
SaveArticleToFile(subject, $"{subject}_all_articles.txt", mainArticle);
using (Bitmap bitmap = (Bitmap)Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "sablon/23964.jpg"))
{
using (Graphics graphics = Graphics.FromImage(bitmap))
{
string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + subject, $"{keywords}.webp");
string text = subject;
Font font = new Font("Arial", 18, FontStyle.Bold);
// Resmin boyutlarını ayarlayın
int maxWidth = 1024;
int maxHeight = 768;
int newWidth = bitmap.Width;
int newHeight = bitmap.Height;
if (newWidth > maxWidth)
{
newWidth = maxWidth;
newHeight = (int)(bitmap.Height * ((float)newWidth / bitmap.Width));
}
if (newHeight > maxHeight)
{
newHeight = maxHeight;
newWidth = (int)(bitmap.Width * ((float)newHeight / bitmap.Height));
}
// Resmi yeniden boyutlandırın
Bitmap resizedBitmap = new Bitmap(bitmap, newWidth, newHeight);
// Yeni resim için grafik oluşturun
Graphics resizedGraphics = Graphics.FromImage(resizedBitmap);
// Yazının boyutunu hesaplayın
SizeF textSize = resizedGraphics.MeasureString(text, font);
// Yazıyı resmin ortasına hizalamak için uygun pozisyonu hesaplayın
float x = (newWidth - textSize.Width) / 2;
float y = (newHeight - textSize.Height) / 2;
// Resim üzerine yazı ekleme
resizedGraphics.DrawString(text, font, Brushes.White, new PointF(x, y));
// Resmi kaydetme
resizedBitmap.Save(filePath, ImageFormat.Webp);
}
} //// Get images from Pexels API
//var images = await GetPexelsImages(imageKeywords, 1, usedImages);
//// Download images to the folder
//await DownloadImages(subject, images);
// Generate subsubjects prompt and get response
string subsubjectsPrompt = GeneratePrompt(subject, false);
string subsubjectsResponse = await GetGpt3Response(subsubjectsPrompt);
string[] subsubjects = subsubjectsResponse.Split('\n');
// Remove blank subsubjects
subsubjects = subsubjects.Where(sub => !string.IsNullOrWhiteSpace(sub)).ToArray();
// Initialize a StringBuilder to hold all articles
StringBuilder allArticles = new StringBuilder(mainArticle);
// Iterate through subsubjects, generate prompts, get responses, and save them to the folder
for (int i = 0; i < subsubjects.Length; i++)
{
string subsubject = subsubjects[i];
Console.WriteLine($"Writing article for subsubject: {subsubject}");
string subPrompt = GeneratePrompt(subsubject, true);
string subArticle = await GetGpt3Response(subPrompt);
// Append subarticle to the StringBuilder
allArticles.AppendLine().AppendLine(subArticle);
}
// Save all articles to the single text file
SaveArticleToFile(subject, $"{subject}_all_articles.txt", allArticles.ToString());
var makale = allArticles.Replace("h1", "h2");
string folderPath = AppDomain.CurrentDomain.BaseDirectory + subject;
string[] imageFiles = Directory.GetFiles(folderPath, "*.webp");
string imageName1 = Path.GetFileNameWithoutExtension(imageFiles[0]);
Console.WriteLine("Articles and images saved successfully.");
}
private static string GeneratePrompt(string subject, bool isSubject, string keyword = null)
{
if (isSubject)
{
return $"Generate a 300-400 word SEO-friendly article in Turkish about " + subject
+ " without a conclusion. Include important sentences about the keyword <strong>" + keyword + "</strong> in strong. Use " + subject + " as an H1 tag at the beginning of the article.";
}
else
{
return $"Write 5 subheadings for a article in Turkish about " + subject + ". List them without adding any additional information";
}
}
private static async Task<string> GetGpt3Response(string prompt)
{
using HttpClient client = new();
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {OpenAiApiKey}");
var data = new
{
model = "gpt-3.5-turbo",
messages = new[]
{
new { role = "system", content = "You are a helpful assistant that generates articles in Turkish." },
new { role = "user", content = prompt }
},
max_tokens = 2000,
n = 1,
temperature = 0.7
};
var response = await client.PostAsync("https://api.openai.com/v1/chat/completions", new StringContent(JsonSerializer.Serialize(data), System.Text.Encoding.UTF8, "application/json"));
var responseJson = await JsonSerializer.DeserializeAsync<JsonElement>(await response.Content.ReadAsStreamAsync());
return responseJson.GetProperty("choices")[0].GetProperty("message").GetProperty("content").GetString().Trim();
}
private static async Task<string[]> GetPexelsImages(string query, int count, HashSet<string> usedImages)
{
using HttpClient client = new();
client.DefaultRequestHeaders.Add("Authorization", PexelsApiKey);
string url = $"https://api.pexels.com/v1/search?query={query}&per_page={count * 5}";
var response = await client.GetAsync(url);
var responseJson = await JsonSerializer.DeserializeAsync<JsonElement>(await response.Content.ReadAsStreamAsync());
var images = new List<string>();
foreach (var photo in responseJson.GetProperty("photos").EnumerateArray())
{
string src = photo.GetProperty("src").GetProperty("original").GetString();
if (!usedImages.Contains(src))
{
images.Add(src);
usedImages.Add(src);
if (images.Count == count)
{
break;
}
}
}
return images.ToArray();
}
private static async Task DownloadImages(string folder, string[] images)
{
using HttpClient client = new();
for (int i = 0; i < images.Length; i++)
{
string img_url = images[i];
// Resim dosyasını indir
var response = await client.GetAsync(img_url);
// Dosya adını oluştur
string fileName = Path.GetFileNameWithoutExtension(img_url);
string fileExt = Path.GetExtension(img_url).ToLower();
string outputExt = fileExt == ".jpg" || fileExt == ".jpeg" || fileExt == ".png" || fileExt == ".bmp" ? ".webp" : fileExt;
string filePath = Path.Combine(folder, $"{keywords}_{i + 1}{outputExt}");
// Resmi WebP formatına dönüştür ve kaydet
using var stream = await response.Content.ReadAsStreamAsync();
using var bmp = new Bitmap(stream);
int maxWidth = 800; // Maximum genişlik
int maxHeight = 450; // Maximum yükseklik
int newWidth = bmp.Width;
int newHeight = bmp.Height;
if (bmp.Width > maxWidth)
{
newWidth = maxWidth;
newHeight = (bmp.Height * maxWidth) / bmp.Width;
}
if (newHeight > maxHeight)
{
newWidth = (newWidth * maxHeight) / newHeight;
newHeight = maxHeight;
}
using var resized = new Bitmap(bmp, newWidth, newHeight);
resized.Save(filePath, ImageFormat.Webp);
}
}
private static HashSet<string> LoadUsedImages()
{
if (File.Exists("used_images.txt"))
{
return new HashSet<string>(File.ReadAllLines("used_images.txt"));
}
else
{
return new HashSet<string>();
}
}
private static void SaveUsedImages(HashSet<string> usedImages)
{
File.WriteAllLines("used_images.txt", usedImages);
}
private static void CreateFolder(string folderName)
{
if (!Directory.Exists(folderName))
{
Directory.CreateDirectory(folderName);
}
}
private static void SaveArticleToFile(string folder, string filename, string content)
{
string validFilename = new string(filename.Select(c => char.IsLetterOrDigit(c) || c == ' ' || c == '.' || c == '_' ? c : '_').ToArray());
File.WriteAllText(Path.Combine(folder, validFilename), content, System.Text.Encoding.UTF8);
}