Skip to content

Commit

Permalink
Fix importer
Browse files Browse the repository at this point in the history
  • Loading branch information
JakubKermes committed Jan 9, 2024
1 parent f6ab32e commit 642ad0d
Show file tree
Hide file tree
Showing 6 changed files with 68 additions and 54 deletions.
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,5 @@ GOOGLE_REDIRECT_URI=http://escooters.blumilk.localhost/login/google/redirect
FACEBOOK_CLIENT_ID=
FACEBOOK_CLIENT_SECRET=
FACEBOOK_REDIRECT_URI=http://escooters.blumilk.localhost/login/facebook/redirect

OPENAI_API_KEY=
51 changes: 19 additions & 32 deletions app/Http/Controllers/RulesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,44 +4,31 @@

namespace App\Http\Controllers;

use App\Http\Resources\CityResource;
use App\Http\Resources\CountryResource;
use App\Http\Resources\ProviderResource;
use App\Models\City;
use App\Models\Country;
use App\Models\Provider;
use App\Models\Rules;

class RulesController
{
public function getRules(): void
public function getRules($country, $city): array
{
}

public function index(): array
{
$cities = CityResource::collection(
City::with("cityAlternativeNames", "cityProviders", "country")
->has("cityProviders")
->whereHas("cityProviders", function ($query): void {
$query->whereNotNull("latitude")->whereNotNull("longitude");
})
->get()
->sortBy("name")
->sortByDesc(fn(City $city): int => $city->cityProviders->count()),
);

$providers = ProviderResource::collection(Provider::all()->sortBy("name"));
$countries = Country::whereHas("cities.cityProviders")
->with(["cities.cityAlternativeNames", "cities.cityProviders"])
->get()
->sortBy("name");

$countries = CountryResource::collection($countries);

return [
"cities" => $cities,
"providers" => $providers,
"countries" => $countries,
$country_id = Country::query()
->where("name", $country)
->first()->id;
$city = City::query()
->where("name", $city)->where("country_id", $country_id)
->first();
$rules = Rules::query()
->where("city_id", $city->id)
->first();

$data = [
"country" => $country,
"city" => $city->name,
"rulesENG" => $rules->rulesENG,
"rulesPL" => $rules->rulesPL,
];

return $data;
}
}
59 changes: 41 additions & 18 deletions app/Services/OpenAIService.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,49 @@

declare(strict_types=1);

namespace App\Http;
namespace App\Services;

use App\Models\City;
use Exception;
use App\Models\Rules;
use OpenAI;

class OpenAIService
{
public function getRules()
public function importRules(bool $force): void
{
$responseENG = "Sorry, we couldn't find any rules for this city.";
$responsePL = "Przepraszamy, nie udało nam się znaleźć żadnych zasad dla tego miasta.";
$data = [];
$countriesKnownToHaveUniformRules = [
"Poland", "Germany", "France", "Spain", "Italy", "Portugal", "Austria", "Czech Republic", "Slovakia", "Hungary", "Romania", "Bulgaria", "Greece", "Sweden", "Finland",
"Norway", "Denmark", "Netherlands", "Belgium", "Switzerland", "Slovenia", "Croatia", "Serbia", "Bosnia and Herzegovina", "Montenegro", "Albania", "North Macedonia",
"Kosovo", "Ukraine", "Belarus", "Lithuania", "Latvia", "Estonia", "Russia", "Ireland", "United Kingdom", "Turkey",
"Cyprus", "Malta", "Iceland", "Luxembourg", "Moldova", "Liechtenstein", "Andorra", "Monaco", "San Marino", "Vatican City",
];

try {
$client = OpenAI::client(env("OPENAI_API_KEY"));
$client = OpenAI::client(env("OPENAI_API_KEY"));
$cities = City::query()->whereHas("cityProviders")->get();

$cities = City::all();
$data = [];
foreach ($cities as $city) {
$data[] = ["city_id" => $city->id, "country_id" => $city->country->id, "city" => $city->name, "country" => $city->country->name, "rulesENG" => null, "rulesPL" => null];
}

foreach ($data as $i) {
$promptENG = "Act as helpful assistant. explain what are the legal limitations for riding electric scooters in " . $i["city"] . ", " . $i["country"] . "? Contain information about: max speed, helmet requirements, allowed ABV, passengers, other relevant details. Be formal, speak english. If you don't have information answering the question, write 'null'";
$promptPL = "Zachowuj się jako pomocny asystant, wyjaśnij jakie są prawa dotyczące jazdy na hulajnogach elektrycznych w " . $i["city"] . ", " . $i["country"] . "? Zawrzyj informacje o: maksymalnej prędkości, potrzebie kasku, dozwolonym alkoholu we krwi, pasażerach, inne. Bądź formalny, mów po polsku. Jeśli nie masz informacji odpowiadających na pytanie, napisz 'null'";

foreach ($cities as $city) {
$data[] = ["city" => $city, "country" => $city->country, "rulesENG" => $responseENG, "rulesPL" => $responsePL];
if (!$force) {
$currentRules = Rules::query()->where("city_id", $i["city_id"])->where("country_id", $i["country_id"])->first();

return $data;
if ($currentRules->rulesENG !== null && $currentRules->rulesPL !== null) {
continue;
}
}

foreach ($data as $i) {
$promptENG = "What are the legal limitations for riding electric scooters in " . $i->name . ", " . $i->country->name . "? Contain information about: max speed, helmet requirements, allowed ABV, passengers, other relevant details. Be formal, end with a legal disclaimer.";
$promptPL = "Jakie są prawa dotyczące jazdy na hulajnogach elektrycznych w " . $i["city"] . ", " . $i["country"] . "? Zawrzyj informacje o: maksymalnej prędkości, potrzebie kasku, dozwolonym alkoholu we krwi, pasażerach, inne. Bądź formalny, zakończ oświadczeniem prawnym.";
$currentRulesInCountry = Rules::query()->where("country_id", $i["country_id"])->first();

if (in_array($i["country"], $countriesKnownToHaveUniformRules, true) && $currentRulesInCountry !== null && $currentRulesInCountry->rulesENG !== null && $currentRulesInCountry->rulesPL !== null && $force === false) {
$i["rulesENG"] = $currentRulesInCountry->rulesENG;
$i["rulesPL"] = $currentRulesInCountry->rulesPL;
} else {
$responseENG = $client->chat()->create([
"model" => "gpt-3.5-turbo",
"messages" => [
Expand All @@ -49,11 +63,20 @@ public function getRules()
],
],
]);
$i["rulesENG"] = $responseENG["choices"][0]["message"]["content"];
$i["rulesPL"] = $responsePL["choices"][0]["message"]["content"];
}

$i["rulesENG"] = $responseENG["choices"][0]["text"];
$i["rulesPL"] = $responsePL["choices"][0]["text"];
if (strlen($i["rulesENG"]) < 700 || strlen($i["rulesPL"]) < 700) {
continue;
}
} catch (Exception $e) {

Rules::query()->updateOrCreate([
"city_id" => $i["city_id"],
"country_id" => $i["country_id"],
"rulesENG" => $i["rulesENG"],
"rulesPL" => $i["rulesPL"],
]);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ public function up(): void
->on("countries")
->onDelete("cascade");

$table->string("rulesENG");
$table->string("rulesPL;");
$table->text("rulesENG");
$table->text("rulesPL");
});
}

Expand Down
3 changes: 3 additions & 0 deletions routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@
declare(strict_types=1);

use App\Http\Controllers\CityProviderController;
use App\Http\Controllers\RulesController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware("auth:sanctum")->get("/user", fn(Request $request): JsonResponse => new JsonResponse($request->user()));

Route::get("/providers", [CityProviderController::class, "index"]);

Route::get("/rules/{country}/{city}", [RulesController::class, "getRules"]);
3 changes: 1 addition & 2 deletions routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
use App\Http\Controllers\CityWithoutAssignedCountryController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\FavoritesController;
use App\Http\OpenAIService;
use Illuminate\Support\Facades\Route;

Route::middleware("guest")->group(function (): void {
Expand Down Expand Up @@ -48,7 +47,7 @@
Route::delete("/delete-city-without-assigned-country/{city}", [CityWithoutAssignedCountryController::class, "destroy"]);
Route::post("/delete-all-cities-without-assigned-country", [CityWithoutAssignedCountryController::class, "destroyAll"]);

Route::get("/importRules", [OpenAIService::class, "getRules"]);
Route::get("/import-rules/{force}", [\App\Services\OpenAIService::class, "importRules"]);
});
});

Expand Down

0 comments on commit 642ad0d

Please sign in to comment.