File size: 4,898 Bytes
5f32fbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<?php

namespace App\Http\Controllers;

use App\Models\PdfData;
use App\Models\Setting;
use App\Models\SettingTwo;
use App\Services\VectorService;
use Exception;
use Illuminate\Http\File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use OpenAI\Laravel\Facades\OpenAI;

class ChatPdfController extends Controller
{
    protected $client;

    protected $settings;

    protected $pinecone;

    public function __construct()
    {
        //Settings
        $this->settings = Setting::first();
        $this->settings_two = SettingTwo::first();
        if ($this->settings?->user_api_option) {
            $apiKeys = explode(',', auth()->user()?->api_keys);
        } else {
            $apiKeys = explode(',', $this->settings?->openai_api_secret);
        }
        $apiKey = $apiKeys[array_rand($apiKeys)];
        config(['openai.api_key' => $apiKey]);

        ini_set('max_execution_time', 140000);
    }

    public function uploadPDF(Request $request)
    {
        $pdf = $request->file('pdf');
        $pdf_content = file_get_contents($pdf->getRealPath());
        $fileName = Str::random(12) . '.pdf';
        Storage::disk('public')->put('temp.pdf', $pdf_content);
        Storage::disk('public')->put($fileName, $pdf_content);

        $uploadedFile = new File(substr("/uploads/$fileName", 1));

        $resPath = "/uploads/$fileName";

        if (SettingTwo::first()->ai_image_storage == 's3') {
            try {
                $aws_path = Storage::disk('s3')->put('', $uploadedFile);
                unlink(substr("/uploads/$fileName", 1));
                $resPath = Storage::disk('s3')->url($aws_path);
            } catch (Exception $e) {
                return response()->json(['status' => 'error', 'message' => 'AWS Error - ' . $e->getMessage()]);
            }
        }

        $chat_id = $request->chat_id;

        PdfData::where('chat_id', $chat_id)->delete();

        // $text = Pdf::getText('uploads/temp.pdf');
        $parser = new \Smalot\PdfParser\Parser;
        $text = $parser->parseFile('uploads/temp.pdf')->getText();

        $page = $text;
        if (! mb_check_encoding($text, 'UTF-8')) {
            $page = mb_convert_encoding($text, 'UTF-8', mb_detect_encoding($text));
        } else {
            $page = $text;
        }

        $countwords = strlen($page) / 2000 + 1;
        for ($i = 0; $i < $countwords; $i++) {
            if (2000 * $i + 4000 > strlen($page)) {
                try {
                    $subtxt = substr($page, 2000 * $i, strlen($page) - 2000 * $i);
                    $subtxt = mb_convert_encoding($subtxt, 'UTF-8', 'UTF-8');
                    $subtxt = iconv('UTF-8', 'UTF-8//IGNORE', $subtxt);
                    $response = OpenAI::embeddings()->create([
                        'model' => 'text-embedding-ada-002',
                        'input' => $subtxt,
                    ]);

                    if (strlen(substr($page, 2000 * $i, strlen($page) - 2000 * $i)) > 10) {

                        $chatpdf = new PdfData;

                        $chatpdf->chat_id = $chat_id;
                        $chatpdf->content = substr($page, 2000 * $i, strlen($page) - 2000 * $i);
                        $chatpdf->vector = json_encode($response->embeddings[0]->embedding);

                        $chatpdf->save();
                    }
                } catch (Exception $e) {
                }
            } else {
                try {
                    $subtxt = substr($page, 2000 * $i, 4000);
                    $subtxt = mb_convert_encoding($subtxt, 'UTF-8', 'UTF-8');
                    $subtxt = iconv('UTF-8', 'UTF-8//IGNORE', $subtxt);
                    $response = OpenAI::embeddings()->create([
                        'model' => 'text-embedding-ada-002',
                        'input' => $subtxt,
                    ]);
                    if (strlen(substr($page, 2000 * $i, 4000)) > 10) {
                        $chatpdf = new PdfData;

                        $chatpdf->chat_id = $chat_id;
                        $chatpdf->content = substr($page, 2000 * $i, 4000);
                        $chatpdf->vector = json_encode($response->embeddings[0]->embedding);

                        $chatpdf->save();
                    }
                } catch (Exception $e) {
                }
            }
        }

        return response()->json(['filename' => $resPath]);
        // } else {
        //     return response()->json(['error' => __('No PDF file uploaded')]);
        // }
    }

    public function getSimiliarContent(Request $request)
    {
        $count = $request->count;
        if ($count == null) {
            $count = 3;
        }

        $vectorService = new VectorService;

        return response()->json(['extra_prompt' => $vectorService->getMostSimilarText($request->prompt, $request->chat_id, $count)]);
    }
}